<?php 
/**
 * Repair parts controller is mainly for warehouse to do inventory control 
 * it study the APOS system and has it's own function of managment 
 * 
 * @author Norman
 *
 */
class RepairpartsController extends Zend_Controller_Action
{

	public static $rCenterMapping;
	public static $rCenterMappRev;
	
	public static $rCenterEmail = array(
			
			1 => "bsxprepair@phonecollection.com.au ",
			2 => "hope.mcmahon@phonecollection.com.au",
			3 => "steven.xie@phonecollection.com.au",
			4 => "boxhill@phonecollection.com.au",
			5 => "highpointic@phonecollection.com.au",
			6 => "cranbourneic@phonecollection.com.au",
			7 => "westlake@phonecollection.com.au",
			8 => "epping@phonecollection.com.au",
			9 => "werribee@phonecollection.com.au",
			10 => "northland@phonecollection.com.au",
			11 => "doncasteric@phonecollection.com.au",
			12 => "knox@phonecollection.com.au",
			13 => "southlandic@phonecollection.com.au",
			14 => "fountaingateic@phonecollection.com.au",
			15 => "parkmoreic@phonecollection.com.au",
			16 => "watergardenic@phonecollection.com.au",
			17 => "arndale@phonecollection.com.au",
			18 => "brimbank@phonecollection.com.au",
			19 => "colonnades@phonecollection.com.au",
			20 => "lu.zhan@phonecollection.com.au",
			21 => "baysideic@phonecollection.com.au",
			23 => "alexpoonhk@yahoo.com",
			24 => "jason.han@phonecollection.com.au",
			30 => "eco3@phonecollection.com.au"			
		);
    public function init(){
    /**
	 *
	 *
	 */   
    	self::$rCenterMapping = unserialize(ARR_RCENTER_MAPPING);
    	self::$rCenterMappRev = unserialize(ARR_RCENTER_REV_MAPPING);
	}

	/**
	 * we have remove the landing page of repair parts to control panel
	 */
    public function indexAction(){
	
		//echo "shomething";	

    
	}
	/**
	 * This is the actual landing page for repair parts
	 */
	public function controlPanelAction(){
		
	}

	/**
	 * This is onceOFF function for warehouse to init the stock
	 * the function is no longer in use
	 */
	public function zNOUSEwarehouseOpeningAction(){
		
		$rProducts = new Model_DbTable_Pr_Prproducts();
		//$rStock = new Model_DbTable_Pr_Prstock();
		
		$file = getcwd()."/tmp/price.csv";
		$fl = fopen($file,"r");
		while(($lineData = fgetcsv($fl))!= FALSE){

			//line Data 0 Code 1 Des  2 3 stock\
			$codeProduct = $lineData[0];
			$titleProduct = $lineData[1];
			$priceA = $lineData[2];
			$priceB = $lineData[3];
			$cate = $lineData[4]; 
			
			//new Products 
			if(!$rProducts->ifExist($codeProduct)){
				
				$idProduct = $rProducts->addProduct($cate, $codeProduct, $titleProduct);
				$rProducts->updatePrice($idProduct, $priceA, $priceB,0);
				//$rStock->insertStockWarehouse($idProduct, $whStock);				
			}
			else{
				
				echo "Duplicated BarCode Should Happen In Opening!<br />";
				
			}
			//insert into stock db 
		}
		
		
	}
	
	/**
	 * this is once off function for shop to init the stock 
	 * the function is no longer in use
	 */
	public function zNOUSEshopOpeningAction(){
		
		
		$rProducts = new Model_DbTable_Pr_Prproducts();
		$rStock = new Model_DbTable_Pr_Prstock();
		
		$idShop = 1;
		if(isset($_GET['shop'])){
			$idShop = $_GET['shop'];
		}
		
		$file = getcwd()."/tmp/pstockshop.csv";
		$fl = fopen($file,"r");
		while(($lineData = fgetcsv($fl))!= FALSE){
		
			//line Data 0 Code 1 Des  2 3 stock\
			$codeProduct = $lineData[0];
			$shopStock = $lineData[3];
				
			//new Products
			if(!$rProducts->ifExist($codeProduct)){
				
				echo "ERROR OCCUR,This Code Not Exist AT All:".$codeProduct;
			}
			else{
				
				$idProduct = $rProducts->getProductID($codeProduct);
				$rStock->updateStockShop($idProduct, $shopStock, $idShop);	
				
			}
			//insert into stock db
		}		
	}
	/**
	 * Using this page to create warehouse GI
	 * 
	 */
	public function warehouseGoodsReceiveAction(){

		
	}	
	
	/**
	 * This is the actual page to save the GI 
	 * GI goods in is only happen in warehouse / shop 0
	 * there are several code to indicate the status of the parts
	 * GI GO TI TO FO EI 
	 */
	public function saveWhGiAction(){
		
		$rProducts = new Model_DbTable_Pr_Prproducts();
		$rStock = new Model_DbTable_Pr_Prstock();
		$rMove = new Model_DbTable_Pr_Prstockmovement();
		$rCounter = new Model_DbTable_Pr_Counter();
		$dateToday = Model_DatetimeHelper::dateToday("");
		$rProductsGn = new Model_DbTable_Pr_Prproductsgi();
		$rGN="";
		$productCode = "";
		$productQty = 0;
		
		if($_POST){
		
			$rGN = "RGN".$dateToday;
			$rGN .= $rCounter->runcounter("RGNCOUNTER");
			
			foreach($_POST['upload'] as $key => $value){
		
			$productCode = "";
			$productTitle = "";
			$productCate = "";
			$productQty = 0;
		
			$arrtmp = explode("|",$value);
			$productCode = strtoupper(trim($arrtmp[0]));
			$qty = trim($arrtmp[1]);
			$supplier = $_POST['supplier'];
			//if not in the datebase then add into product database
			
			if(!$rProducts->ifExist($productCode)){
						
				echo $productCode." is not exist"."<br/>";
			}
			else{
				//item already EXIST
				$idProduct = $rProducts->getProductID($productCode);
				$rStock->increaseStockWarehouse($idProduct, $qty);
				$rProductsGn->addGiRecord($idProduct, $productCode, $qty, $supplier, $_POST['staff_name'], $dateToday, $rGN);
			}
			
			$rMove->addMovement(1, $idProduct, $qty,$_POST['staff_name'],0,$rGN);
			
			}

		}
		
		$this->view->RGN = $rGN;
	}
	
	
	/**
	 * API function for create pr barcode
	 */
	public function createPrBarcodeAction(){
	
		$rProducts = new Model_DbTable_Pr_Prproducts();
		$rStock = new Model_DbTable_Pr_Prstock();
		$rMove = new Model_DbTable_Pr_Prstockmovement();
		$rCounter = new Model_DbTable_Pr_Counter();
		$dateToday = Model_DatetimeHelper::dateToday("");
		$rGN="";
		$productCode = "";
		$productQty = 0;
	
		if($_POST){
	
			$rGN = "RGN".$dateToday;
			$rGN .= $rCounter->runcounter("RGNCOUNTER");
				
			foreach($_POST['upload'] as $key => $value){
	
				$productCode = "";
				$productTitle = "";
				$productCate = "";
				$productQty = 0;
	
				$arrtmp = explode("|",$value);
				$productCode = strtoupper(trim($arrtmp[0]));
				$productCate = trim($arrtmp[1]);
				$productTitle = trim($arrtmp[2]);
				$qty = trim($arrtmp[3]);
	
				//if not in the datebase then add into product database
	
				if(!$rProducts->ifExist($productCode)){
	
					$idProduct = $rProducts->addProduct($productCate, $productCode,$productTitle);
					$rStock->insertStockWarehouse($idProduct, $qty);
				}
				else{
					//item already EXIST
					$idProduct = $rProducts->getProductID($productCode);
					$rStock->increaseStockWarehouse($idProduct, $qty);
				}
					
				$rMove->addMovement(1, $idProduct, $qty,$_POST['staff_name'],0,$rGN);
			}
	
		}
	
		$this->view->RGN = $rGN;
	}
	
	/**
	 * This function is not very imporant
	 * this function is for print barcode (code 128b)
	 * for shop to use when there was no barcode on the parts
	 * now all parts has barcode sticker on the bag this function 
	 * is no longer important
	 * 
	 */
	public function printBarcodeAction(){
		
		$cate = $this->_getParam('cate');
		$this->view->idCate = $cate;
		$rProducts = new Model_DbTable_Pr_Prproducts();		
		$this->view->plist = $rProducts->listProductsByCate($cate);
				
	}
	
	/**
	 * This is the page for warehouse to tranfer the parts 
	 * to Create the TI function 
	 * the warehouse can transfer more than one parts at the same time 
	 * and create RKT for it 
	 */
	public function transferPartsToShopAction(){
		
		$idShop = 1;
		$tmpvar=$this->_getParam('shop');
		if($tmpvar != ""){
			$idShop = $tmpvar;
		}
		
		$this->view->idShop = $idShop;
		
		$rProduct = new Model_DbTable_Pr_Prproducts();
			
		$this->view->pList = $pList = $rProduct->listAllProducts();
		
		
	}
	/**
	 * This is actual saving page of create RKT
	 * 
	 */
	public function saveWhTiAction(){
		
		
		$rProducts = new Model_DbTable_Pr_Prproducts();
		$rStock = new Model_DbTable_Pr_Prstock();
		$rMove = new Model_DbTable_Pr_Prstockmovement();		
		$productCode = "";
		$productQty = 0;
		
		$rCounter = new Model_DbTable_Pr_Counter();
		$dateToday = Model_DatetimeHelper::dateToday("");
		$rKT="";
		
		$this->view->idShop = 0;
		
		if($_POST){
			
			$this->view->idShop = $_POST['id_shop'];
			
			
			$rKT = "RKT".$dateToday;
			
			if($_POST['id_shop'] == 23){
			
				$rKT = "RKS".$dateToday;
			}
			
			
			$rKT .= $rCounter->runcounter("RKTCOUNTER");
			
			foreach($_POST['upload'] as $key => $value){
			
				$productCode = "";
				$productQty = 0;
			
				$arrtmp = explode("[",$value);
			
				$productCode = $arrtmp[0];
				$qty = (int)trim(str_replace("]","",$arrtmp[1]));
			
				//It should be in the Database 
			
				if(!$rProducts->ifExist($productCode)){
					
					echo "ERROR OCCUR,This Code Not Exist AT All:".$productCode;
				}
				else{
					//item already EXIST
					$idProduct = $rProducts->getProductID($productCode);
					
					//warehouse stock -
					$rStock->descreaseStockWarehouse($idProduct, $qty);					
					//shop stock + 
					$rStock->increaseStockShop($idProduct, $qty, $_POST['id_shop']);
					//record movement 
					$typeMove = 3;
					if($_POST['id_shop'] == 23){
						
						$typeMove = 31;
					}
					$rMove->addMovement($typeMove, $idProduct, $qty,$_POST['staff_name'],$_POST['id_shop'],$rKT);
					
					
				}
			
			}	

			$this->view->RKT = $rKT;
			
			
		}		
		
	}
	
	/**
	 * This page is not very important 
	 * it shows all he hardcoded category link of print barcode ans stock take 
	 */
	public function warehouseStockMainAction(){
		
	}
	
	/**
	 * This page is also called Modify price and Descripton 
	 * it shows the barcode in the category 
	 * it shows the descripton of the products and available to edit price 
	 * the authorized staff can modify the price and descripton using the password
	 * it also able to change the category by click the link 
	 */
	public function warehouseStockTakeAction(){
		
		$idCate = $this->_getParam('cate');
		$showPrice= "";
		$showPrice= $this->_getParam('show');
		$this->view->showPrice = $showPrice;
		$priceChange = false;
		
		$rCate = new Model_DbTable_Pr_Category();
		$rPriceCate = new Model_DbTable_Pr_Pricecategory();
		$this->view->rActList = $rPriceCate->listAllActiveEdit(); 
		$this->view->cList = $rCate->listCategory();
		
		
		$this->view->dateToday = $dateToday = Model_DatetimeHelper::dateToday();
		
		$rProducts = new Model_DbTable_Pr_Prproducts();
		
		if($_POST){
				
			if($_POST["password"]=="Office051788"){
		
				foreach($_POST["price_a"] as $key => $v){
						
					$line = $rProducts->getProduct($key);
						
					foreach($this->view->rActList as $ka => $va){
						
						$cateString = $va['id_price_category'];
						if(isset($_POST[$cateString][$key])){
							//var_dump($cateString,$key,$line);
							
							if($_POST[$cateString][(string)$key] != $line[$cateString]){
								
								$rProducts->updateSinglePrice($key, $cateString, $_POST[$cateString][$key]);
								$priceChange = true;
							}	
							
						}
					}
					
					//if($v != $line["price_a"] || $_POST["price_b"][$key] != $line["price_b"] || $_POST["price_c"][$key] != $line["price_c"]){
					//	$rProducts->updatePrice($key, $v,$_POST["price_b"][$key], $_POST["price_c"][$key],$dateToday);
					//	$priceChange = true;
					// }
					
					if(isset($_POST["act_cost"])){
					$rProducts->updateCost($key, $_POST["act_cost"][$key], $dateToday);
					}
					$rProducts->updateDes($key, $_POST["des"][$key]);
					
					
				}
				if($priceChange){
					$updates = new Model_DbTable_Updatenews();
					$check = $updates->ifPriceUpdate(Model_DatetimeHelper::dateToday());
					//check multi update
					if(!$check){
						$updates->addUpdate(5,"Repair Parts Price/Description Has been Updated on ".Model_DatetimeHelper::dateToday(),0);
					}
				}
				echo "Price Updated!!";
			}
			else{
		
				echo "Password Wrong!!";
			}

		}		
		
		$this->view->idCate = $idCate;
		
		$this->view->pList = $rProducts->listProductsByCate($idCate);
		

		
	}
	
	/**
	 * Check all stock  function is for shop staff to check the current stock 
	 * it show all current shop stock and warehouse stock , 
	 * 
	 */
	public function stockListAllAction(){
		
	
		$idCate = 0;
		$idCate = $this->_getParam('cate');
	
		$rProducts = new Model_DbTable_Pr_Prproducts();
		
		$rCate = new Model_DbTable_Pr_Category();
		$this->view->cList = $rCate->listCategory();
		
	
		$this->view->idCate = $idCate;
	
		$this->view->pList = $rProducts->listProductsByCate($idCate);
	
		$this->view->dateToday = Model_DatetimeHelper::dateToday();
	
	}
	
	/**
	 * This is the page to create warehouse adjustment 
	 * the page is original for adjust in however  if input (-) negative numbers 
	 * it will be adjust out 
	 */
	public function warehouseAdjustInAction(){
		
	}
	
	/**
	 * this is the actual page to create RAD
	 * the inital notes called AI or AO means adjust in or adjust out 
	 * then it all change to AD
	 */
	public function saveWhAdjustInAction(){
		
		
		$rProducts = new Model_DbTable_Pr_Prproducts();
		$rStock = new Model_DbTable_Pr_Prstock();
		$rMove = new Model_DbTable_Pr_Prstockmovement();
		$productCode = "";
		$productQty = 0;
		$idWarehouse = 0;
		$dateTody = Model_DatetimeHelper::dateToday("");
		$timeNow = Model_DatetimeHelper::timeNow("");
		$aINo = "AD".$dateTody.$timeNow;
		
		if($_POST){
		
		
		
			foreach($_POST['upload'] as $key => $value){
					
				$productCode = "";
				$productQty = 0;
					
				$arrtmp = explode("[",$value);
		
				$productCode = $arrtmp[0];
				$qty = (int)trim(str_replace("]","",$arrtmp[1]));
					
				//It should be in the Database
					
				if(!$rProducts->ifExist($productCode)){
		
					echo "ERROR OCCUR,DATA NOT SAVE,This Code Not Exist AT All:".$productCode;
				}
				else{
					//item already EXIST
					$idProduct = $rProducts->getProductID($productCode);
		
					//shop stock -
					$rStock->increaseStockWarehouse($idProduct, $qty);
					//record movement
					if($qty >0){
						$rMove->addMovement(5, $idProduct, $qty,$_POST['staff_name'],$idWarehouse,$aINo,$_POST['move_reason']);
					}
					else{
						$rMove->addMovement(6, $idProduct, 0 - $qty,$_POST['staff_name'],$idWarehouse,$aINo,$_POST['move_reason']);
					}
					
					$tmpStock = $rStock->getWarehouseStock($idProduct);
					$rMove->addMovement(9, $idProduct, $tmpStock,$_POST['staff_name'],$idWarehouse,$aINo,$_POST['move_reason']);
						
				}
					
			}
		
		
		}
		
		$this->view->AINO = $aINo;
		$this->view->reason = $_POST['move_reason'];
	}
	
	
	/**
	 * Stock alert function is exactly same as check all stock functon , however this is for warehouse
	 * it show the all numbers 3 and it also show last two weeks product sales 
	 * 
	 */
	public function stockAlertAction(){
		
		$idCate = 0;
		$idCate = $this->_getParam('cate');
		
		$rProducts = new Model_DbTable_Pr_Prproducts();
		$rCate = new Model_DbTable_Pr_Category();
		$this->view->cList = $rCate->listCategory();	
		
		$this->view->idCate = $idCate;
		
		$rList = $rProducts->listProductsByCate($idCate);
		
		$this->view->dateToday = Model_DatetimeHelper::dateToday();
		$dateTwoWeeks =  Model_DatetimeHelper::dateToday();
		$dateTwoWeeks = Model_DatetimeHelper::adjustDays("sub",$dateTwoWeeks,14);
		$dateOneWeek = Model_DatetimeHelper::adjustDays("sub",Model_DatetimeHelper::dateToday(),7);
		$this->view->dateTwoWeeks = $dateTwoWeeks;
		$this->view->dateOneWeek = $dateOneWeek;
		
		echo $dateOneWeek;
		
	
		if($_POST){
			//disactive all
			//var_dump($_POST);
			
			foreach($rList as $key => $v){
				if(isset($_POST['active'][$v['id_product']])){
					
					$rProducts->activeProduct($v['id_product']);
				}
				else{
					$rProducts->activeProduct($v['id_product'],true);
				}
				
			}
			
		echo "Record Saved<br/>";
		}
		$rList = $rProducts->listProductsByCate($idCate);
		$this->view->pList = $rList;
		
	}
	/**
	 * 
	 * 
	 * This is the new parts borrow procedure.
	 * When borrow parts,it start from the lender not the borrower 
	 * When the Job arrive to the borrow part, they need to confirm.
	 * it will show in company info page 
	 * When lend , the lender just inital the lending action , there  will be no stock change
	 * if borrow part not confirm , nothing will happen.
	 * so the borrow part will have stock Gain , lender part has stock Lost,
	 * so the Lender part will force borrow part to confirm.
	 * since it should be no stock for borrow part, borrow part should have negative Numbers 
	 * 
	 */
	public function moveWithoutJobidApplyAction(){ 
		
		$idShop = $this->_getParam('shop');
		$idJob = $this->_getParam('jobid');
		$shopHead = $this->_getParam('shophead');
		
		$this->view->erorMessage = "";
		
		$rJob = new Model_DbTable_Repairjob();
		$rProduct = new Model_DbTable_Pr_Prproducts();
		$rCategoryModel = new Model_DbTable_Pr_Categorymodel();
		$rStatus = new Model_DbTable_Repairstatusrecord();
		$rMove = new Model_DbTable_Pr_Prstockmovement();
		$arrPlist = array();
		if($idJob!="parts"  && $idJob!="BORROWPARTS"){
		$job2List = $rMove->listByJobCodeId(2, $idJob);
		$job7List = $rMove->listByJobCodeId(7, $idJob);
		$mList = array_merge($job2List,$job7List);
		foreach($mList as $item){
			$codePro = $rProduct->getProduct($item['id_product']);
			$arrPlist[] = $item['qty_product']." x [".$codePro['code_product']."][".$codePro['title_product']."] Has Been Recorded!";
		}
		}
		//$mList = $rMove->getPartMoveByJobID($idJob);
		//d($mList);
		$this->view->arrPlist = $arrPlist;
		
		$this->view->freeze = false;
		
					
		if($idJob=="" || $idShop==""){				

			$this->view->errorMessage = "ERROR OCCUR, DO NOT PROCEED,PLEASE START FROM THE STATUS PAGE";
		}
		
		else{
						
			if($idJob == "BORROWPARTS"){
				if($idShop < 10){
					$idJob = "80".$idShop.Model_DatetimeHelper::dateToday("").Model_DatetimeHelper::timeNow("");
				}
				else{
					$idJob = "8".$idShop.Model_DatetimeHelper::dateToday("").Model_DatetimeHelper::timeNow("");
				}
			}
			
			if(substr($idJob,0,1) == 8 || strtolower($idJob) == "parts"){
				
				$pList = $rProduct->listAllActive();
			}
			else{
				$lastStatus = $rStatus->getLastStatus($idJob);
				
				if($lastStatus[0]['id_status']>= 80){
					
					$this->view->freeze = true;
				}
				
				
				$catRow = $rJob->getJob($idJob);
				$idCate = $rCategoryModel->getIdCategory(trim($catRow['mobile_model']));
				$idCate = $idCate['id_category'];
				if(!$idCate || $idCate == 99){
					
					$pList = $rProduct->listAllActive();
				}
				else{
					
					$pList = $rProduct->listAllActiveCategory($idCate);
				}
				
			}
			
			
			$this->view->idshop = $idShop;
			$this->view->idjob = $idJob;	
			$this->view->shopHead = $shopHead;		
		}
		
		
		
			
		$this->view->pList = $pList;
				
	}
	
	/**
	 * This is the latest version of parts record 
	 * parts record is the page to create GO function which is sales 
	 * this funcon with some features 
	 * 1. it records the parts consumption , if it is negative number , it is error correction EI
	 * 2. it show you how many parts has been already used for this job 
	 * 3. it give hint if the parts is recorded the stock qty will be -1 
	 * 4. it give you the power to borrow from others 
	 * @todo you should not borrow from yourself, it is done  
	 */
	public function partsRecordWithBorrowAction(){ 
		
		$idShop = $this->_getParam('shop');
		$idJob = $this->_getParam('jobid');
		$shopHead = $this->_getParam('shophead');
		$this->view->erorMessage = "";
		
		$rJob = new Model_DbTable_Repairjob();
		$rProduct = new Model_DbTable_Pr_Prproducts();
		$rCategoryModel = new Model_DbTable_Pr_Categorymodel();
		$rStatus = new Model_DbTable_Repairstatusrecord();
		$rMove = new Model_DbTable_Pr_Prstockmovement();
		$arrPlist = array();
		if($idJob!="parts"  && $idJob!="BORROWPARTS"){
		$job2List = $rMove->listByJobCodeId(2, $idJob);
		$job7List = $rMove->listByJobCodeId(7, $idJob);
		$mList = array_merge($job2List,$job7List);
		foreach($mList as $item){
			$codePro = $rProduct->getProduct($item['id_product']);
			$arrPlist[] = $item['qty_product']." x [".$codePro['code_product']."][".$codePro['title_product']."] Has Been Recorded!";
		}
		}
		//$mList = $rMove->getPartMoveByJobID($idJob);
		//d($mList);
		$this->view->arrPlist = $arrPlist;
		
		$this->view->freeze = false;
		
					
		if($idJob=="" || $idShop==""){				

			$this->view->errorMessage = "ERROR OCCUR, DO NOT PROCEED,PLEASE START FROM THE STATUS PAGE";
			
			return false;		
			
		}else{
						
			if($idJob == "BORROWPARTS"){
				if($idShop < 10){
					$idJob = "80".$idShop.Model_DatetimeHelper::dateToday("").Model_DatetimeHelper::timeNow("");
				}
				else{
					$idJob = "8".$idShop.Model_DatetimeHelper::dateToday("").Model_DatetimeHelper::timeNow("");
				}
			}
			
			if(substr($idJob,0,1) == 8 || strtolower($idJob) == "parts"){
				
				$pList = $rProduct->listAllActive();
			}
			else{
				$lastStatus = $rStatus->getLastStatus($idJob);
				
				if($lastStatus[0]['id_status']>= 80){
					
					$this->view->freeze = true;
				}
				
				
				$catRow = $rJob->getJob($idJob);
				$idCate = $rCategoryModel->getIdCategory(trim($catRow['mobile_model']));
				$idCate = $idCate['id_category'];
				if(!$idCate || $idCate == 99){
					
					$pList = $rProduct->listAllActive();
				}
				else{
					
					$pList = $rProduct->listAllActiveCategory($idCate);
				}
				
			}
			
			
			$this->view->idshop = $idShop;
			$this->view->idjob = $idJob;	
			$this->view->shopHead = $shopHead;		
		}
		
		
		
			
		$this->view->pList = $pList;
				
	}
	/**
	 * This function has been replaced by parts record with borrow 
	 */
	public function partsRecordAction(){
	
		$idShop = $this->_getParam('shop');
		$idJob = $this->_getParam('jobid');
		$shopHead = $this->_getParam('shophead');
		$this->view->erorMessage = "";
			
		if($idJob=="" || $idShop==""){
	
			$this->view->errorMessage = "ERROR OCCUR, DO NOT PROCEED,PLEASE START FROM THE STATUS PAGE";
		}
	
		else{
			$this->view->idshop = $idShop;
			$this->view->idjob = $idJob;
			$this->view->shopHead = $shopHead;
		}
	
	
		$rProduct = new Model_DbTable_Pr_Prproducts();
			
		$this->view->pList = $pList = $rProduct->listAllActive();
	
	}	
	
	
	/**
	 * this is stand along saving function for lend parts
	 * this will only create the lend record , no stock will be adjusted 
	 * since we are using apos as stock control 
	 */
	public function saveMoveWithoutJobidApplyAction(){
		
		date_default_timezone_set("Australia/Melbourne");
	
		$rProducts = new Model_DbTable_Pr_Prproducts();
		$rStock = new Model_DbTable_Pr_Prstock();

		$loan = new Model_DbTable_Pr_Loan();
		$stDetail = new Model_DbTable_Roster_Stafflogindetail();
		$productCode = "";
		$productQty = 0;
		$this->view->idShop = 0;
		$this->view->errorMessage = "";
		$arrRes = array();
		$errFlag = false;
	
		if($_POST){
	
	
			$this->view->idShop = $_POST['shop_from'];
	
			foreach($_POST['upload'] as $key => $value){
					
				$productCode = "";
				$productQty = 0;
				$idBorrow = 0;
					
				$arrtmp = unserialize(gzuncompress(base64_decode(trim($value))));
					
				$productCode = $arrtmp[0];
				$qty = (int)$arrtmp[1];	
				$isBorrow = $arrtmp[2];
				
				
				$idJob = $_POST['id_job'];
				$shopFrom = $_POST['shop_from'];
				
				$shopTo = $arrtmp[3];
				
				//$idProduct =$rProducts->getProductID($productCode);
				$bCode = "";
				
				$idMove = 0;
				//$shortIdJob = 
				// id Product
				//YEAR/MONTH/DATE/HOUR/MIN
					
				//It should be in the Database
			//	$loan->addLoan($bCode, $idJob, $idStockmove, $shopFrom, $shopTo, $idProduct, $codeProduct, $dateLoan, $timeRecord, $idStaff)
				if(strtoupper(substr(trim($idJob),0,1)) == 'L' || strtoupper(substr(trim($idJob),0,1)) == 'C'){
					if(strlen($idJob)!=10){
						
						$this->view->errorMessage.= "ERROR, Invoice Can Not Be Accepted, Record(s) Can NOT Save!!<br />";
						$errFlag = true;
					}
					
				}
				
				if(!$rProducts->ifExist($productCode) || $errFlag){
	
					$this->view->errorMessage.= "ERROR, BarCode '".$productCode."' NOT EXIST, Record(s) Can NOT Save!!<br />";
				}
				else{
					//item already EXIST
					$idProduct = $rProducts->getProductID($productCode);
					
					$borrowOk = false;
					
						// if it is borrow with out job id 
						
						//shop stock -
						/* Borrow with job id , disabled for this function ,no need 
						if(substr($_POST['id_job'],0,1) != 8){
						$rStock->descreaseStockShop($idProduct,$qty,$_POST['id_shop']);
						//record movement
						if($qty>0){
							$idMove = $rMove->addMovement(2, $idProduct, $qty,$_POST['staff_name'],$_POST['id_shop'],$_POST['id_job']);
						}
						else{
							$idMove = $rMove->addMovement(7, $idProduct, 0 - $qty,$_POST['staff_name'],$_POST['id_shop'],$_POST['id_job']);
						}
						}
						*/
					if($isBorrow){
					
						$bCode = $loan->buildBorrowCode($shopFrom, $shopTo, $idProduct, $idJob);
					
						$stLine = $stDetail->checkPasswordCorrect(Model_EncryptHelper::hashsha(trim($_POST['att_pass'])));
						//var_dump($stLine);
						if($stLine){
							$loan->addLoan($bCode, $idJob, $idMove, $shopFrom, $shopTo, $idProduct, $productCode,Model_DatetimeHelper::dateToday(),Model_DatetimeHelper::timeNow(), $stLine['id'],$qty);
							$borrowOk = true;
							
							$arrtmp[] = $bCode;
							
							//Sending Emails 
							$url = "Borrowing ".$qty." x [".$productCode."] From  ".$shopFrom." To ".$shopTo." Please Follow Link to Confrim:<br /> ";
							$url .= "http://".WEB_IP."/repairparts/confirm-borrow/bcode/{$bCode}";
							
							$mail = new Model_Emailshandler();
							@$mail->sendNormalEmail(self::$rCenterEmail[$shopTo],"Confirm Borrow Part(s), Follow Link Please", $url,"order@phonecollection.com.au");
							@$mail->sendNormalEmail(self::$rCenterEmail[$shopFrom],"Confirm Borrow Part(s), Follow Link Please", $url,"order@phonecollection.com.au");
						}
						else{
							
							$this->view->errorMessage = "WRONG PASSWORD, NO BORROW CODE CREATED, PLEASE GOBACK AND DO AGAIN!!";
							
						}
					}
					$arrRes[] = $arrtmp;	
				}
					
			}
	
		$this->view->arrRes = $arrRes;
		}
	
	
	
	}
	
	/**
	 * This funcon is current functon to create shop GO and borrow record 
	 * this function do the following action 
	 * 
	 * 1. record the GO action 
	 * 2. deduct the shop stock 
	 * 3. create record in shop loan
	 * 
	 * 
	 * 
	 */
	public function saveShopGoWithBorrowAction(){
		
		date_default_timezone_set("Australia/Melbourne");
	
		$rProducts = new Model_DbTable_Pr_Prproducts();
		$rStock = new Model_DbTable_Pr_Prstock();
		$rMove = new Model_DbTable_Pr_Prstockmovement();
		$loan = new Model_DbTable_Pr_Loan();
		$stDetail = new Model_DbTable_Roster_Stafflogindetail();
		$productCode = "";
		$productQty = 0;
		$this->view->idShop = 0;
		$this->view->errorMessage = "";
		$arrRes = array();
		$errFlag = false;
	
		if(isset($_POST['sub_upload'])){
	
	
			$this->view->idShop = $_POST['id_shop'];
	
			foreach($_POST['upload'] as $key => $value){
					
				$productCode = "";
				$productQty = 0;
				$idBorrow = 0;
					
				$arrtmp = unserialize(gzuncompress(base64_decode(trim($value))));
					
				$productCode = $arrtmp[0];
				$qty = (int)$arrtmp[1];	
				$isBorrow = $arrtmp[2];
				
				
				$idJob = $_POST['id_job'];
				$shopFrom = $arrtmp[3];
				
				$shopTo = $_POST['id_shop'];
				
				//$idProduct =$rProducts->getProductID($productCode);
				$bCode = "";
				
				$idMove = 0;
				//$shortIdJob = 
				// id Product
				//YEAR/MONTH/DATE/HOUR/MIN
					
				//It should be in the Database
			//	$loan->addLoan($bCode, $idJob, $idStockmove, $shopFrom, $shopTo, $idProduct, $codeProduct, $dateLoan, $timeRecord, $idStaff)
				if(strtoupper(substr(trim($idJob),0,1)) == 'L' || strtoupper(substr(trim($idJob),0,1)) == 'C'){
					if(strlen($idJob)!=10){
						
						$this->view->errorMessage.= "ERROR, Invoice Can Not Be Accepted, Record(s) Can NOT Save!!<br />";
						$errFlag = true;
					}
					
				}
				if(!$rProducts->ifExist($productCode) || $errFlag){
	
					$this->view->errorMessage.= "ERROR, BarCode '".$productCode."' NOT EXIST, Record(s) Can NOT Save!!<br />";
					return false;
				}else{
					//item already EXIST
					$idProduct = $rProducts->getProductID($productCode);					
					
					$borrowOk = false;
					
					if($isBorrow){
							
						$bCode = $loan->buildBorrowCode($shopFrom, $shopTo, $idProduct, $idJob);
							
						$stLine = $stDetail->checkPasswordCorrect(Model_EncryptHelper::hashsha(trim($_POST['att_pass'])));
						//var_dump($stLine);
						if($stLine){
							
							$borrowOk = true;
								
							$arrtmp[] = $bCode;
							if(substr($_POST['id_job'],0,1) != 8){
							$rStock->descreaseStockShop($idProduct,$qty,$_POST['id_shop']);
							//record movement
								if($qty>0){
									$idMove = $rMove->addMovement(2, $idProduct, $qty,$_POST['staff_name'],$_POST['id_shop'],$_POST['id_job']);
								}
								else{
									$idMove = $rMove->addMovement(7, $idProduct, 0 - $qty,$_POST['staff_name'],$_POST['id_shop'],$_POST['id_job']);
								}
							}
							$loan->addLoan($bCode, $idJob, $idMove, $shopFrom, $shopTo, $idProduct, $productCode,Model_DatetimeHelper::dateToday(),Model_DatetimeHelper::timeNow(), $stLine['id'],$qty);
							
							//Sending Emails
							$url = "Borrowing ".$qty." x [".$productCode."] From  ".$shopFrom." To ".$shopTo." Please Follow Link to Confrim:<br /> ";
							$url .= "http://".WEB_IP."/repairparts/confirm-borrow/bcode/{$bCode}";
								
							$mail = new Model_Emailshandler();
							@$mail->sendNormalEmail(self::$rCenterEmail[$shopTo],"Confirm Borrow Part(s), Follow Link Please", $url,"order@phonecollection.com.au");
							@$mail->sendNormalEmail(self::$rCenterEmail[$shopFrom],"Confirm Borrow Part(s), Follow Link Please", $url,"order@phonecollection.com.au");
							//@$mail->sendNormalEmail('eco3@phonecollection.com.au',"Confirm Borrow Part(s), Follow Link Please", $url,"order@phonecollection.com.au");
						}
						else{
								
							$this->view->errorMessage = "WRONG PASSWORD, NO BORROW CODE CREATED, PLEASE GOBACK AND DO AGAIN!!";
							return false;	
						}
					}else{
						
						// if it is borrow with out job id
						
						//shop stock -
						if(substr($_POST['id_job'],0,1) != 8){
							$rStock->descreaseStockShop($idProduct,$qty,$_POST['id_shop']);
							//record movement
							if($qty>0){
								$idMove = $rMove->addMovement(2, $idProduct, $qty,$_POST['staff_name'],$_POST['id_shop'],$_POST['id_job']);
							}
							else{
								$idMove = $rMove->addMovement(7, $idProduct, 0 - $qty,$_POST['staff_name'],$_POST['id_shop'],$_POST['id_job']);
							}
						}
						
						
					}
					
					
						
					
					
					$arrRes[] = $arrtmp;	
				}
					
			}
	
		$this->view->arrRes = $arrRes;
		}
	
	
	
	}	
	
	/**
	 * Confirm borrow function is for the shop who lend the parts to confirm this is happending
	 * when borrow is create, email will send to the lend shop with link 
	 * the lend shop then using this page to cofirm the borrow 
	 * only after the lend shop confirmed , the stock in lend shop will be deduct
	 * 
	 */
	
	public function confirmBorrowAction(){
		$loan = new Model_DbTable_Pr_Loan();
		$stDetail = new Model_DbTable_Roster_Stafflogindetail();
		
		$rStock = new Model_DbTable_Pr_Prstock();
		$rMove = new Model_DbTable_Pr_Prstockmovement();
		$rPro = new Model_DbTable_Pr_Prproducts();
		
		$bCode = $this->_getParam("bcode");
		
		if($bCode!=""){
			
		$borrowLine = $loan->getByBorrowCode($bCode);
			
		$this->view->borrowLine = $borrowLine;
		$this->view->stLine = $stDetail->getDetail($borrowLine['id_staff']);
		$this->view->rpLine = $rPro->getProduct($borrowLine['id_product']);
		
		//var_dump($borrowLine);
		
		if($_POST){ 
				
				if(isset($_POST['btn_check'])){
					$bcode = trim($_POST['bcode']);
					
					$this->_redirect("/repairparts/confirm-borrow/bcode/".$bcode);
					
				}else{
			
				$passwordLine = $stDetail->checkPasswordCorrect(Model_EncryptHelper::hashsha(trim($_POST['pwd'])));
				// you can not confirm yourself
				$idConfirm = $passwordLine['id'];
				
				$idStaffBorrow = $borrowLine['id_staff'];
					
			if($passwordLine){
				
				if($passwordLine['id'] != $idStaffBorrow ){
					
				
					$loan->confirmBorrowByCode($bCode, $passwordLine['id']);
					$rStock->increaseStockShop($borrowLine['id_product'], 0 - $borrowLine['qty_product'], $borrowLine['shop_from']);
					$rMove->addMovement(4,$borrowLine['id_product'], $borrowLine['qty_product'], "BorrowFrom",$borrowLine['shop_from'],$bCode);
					$rStock->increaseStockShop($borrowLine['id_product'], $borrowLine['qty_product'], $borrowLine['shop_to']);
					$rMove->addMovement(3,$borrowLine['id_product'], $borrowLine['qty_product'], "LendTo",$borrowLine['shop_to'],$bCode);
									
					echo "Borrow Code Confirmed, You may CLose the Page Now";
					// changing the stock  accordinglly
					
					// add move status 
					
					
				}
				else{
					echo "You can Not Confirm The Borrow Action Of Yourself,You Will Need Another One Confirm For You";
				}
				
			}
			else{
				
				echo "Password Is Incorrect";
			}
				}
		}
		
		}	
	}

	
	public function phoneStockTakeAction(){
		$shopHead = $this->_getParam('shop');
		$repaircenter = unserialize(ARR_RCENTER_MAPPING);
		$repairJob = new Model_DbTable_Repairjob();
		$transRecord = new Model_DbTable_Pr_Transrecord();
		$lastStatusList = new Model_DbTable_Repairstatusrecord();
		$staffDetail = new Model_DbTable_Roster_Stafflogindetail();
		$pStock = new Model_DbTable_Phonestocktake();
		
		$thisMonday = Model_DatetimeHelper::getThisWeekMonday();
		$searchResult = $repairJob->listUnfinishedJobByShop($shopHead);
		
		$shopId = $repaircenter[$shopHead];
		if($shopId < 10){
			$shopId = "0".$shopId;	
		}

		$orderNo = "PH".$shopId.Model_DatetimeHelper::getThisWeekMonday("");

		$jobList = array();
		foreach ($searchResult as $k => $v){
			$theLastStatus = $lastStatusList->getLastStatus($v['id_job']);
		
			if($theLastStatus[0]['id_status'] == $v['id_status'] and $theLastStatus[0]['time_record'] == $v['time_record'] && $v['is_qf'] != 1){
				$jobList[] = $v;
			}
		}
		
		foreach ($jobList as $k => $v){
			$check = $pStock->checkExist($v['id_job'],$thisMonday);
			
			$idStatus = 0;
			$jobCheck = $transRecord->getLastTrack($v['id_job']);
			if($jobCheck && $jobCheck['id_status'] == 8){
				$idStatus = 8;
			}elseif ($jobCheck && $jobCheck['id_status'] == 12){
				$idStatus = 12;
			}
			if(!$check){
				if($idStatus == 8){ //HeadOffice
					$pStock->addResult($orderNo, $v['id_job'], $thisMonday, $v['customer_name'], $v['mobile_model']." ".$v['mobile_color'],3);
				}elseif($idStatus == 12){ //Tech
					$pStock->addResult($orderNo, $v['id_job'], $thisMonday, $v['customer_name'], $v['mobile_model']." ".$v['mobile_color'],2);
				}else{
					$pStock->addResult($orderNo, $v['id_job'], $thisMonday, $v['customer_name'], $v['mobile_model']." ".$v['mobile_color']);
				}
				
			}else{
				if($idStatus == 8){
					$pStock->updateResult($check['id'], '110', 3, Model_DatetimeHelper::dateToday());
				}elseif($idStatus == 12){
					$pStock->updateResult($check['id'], '110', 2, Model_DatetimeHelper::dateToday());
				}
			}
			
		}
		$list = array();
		$handList = array();
		
		$tmp = $pStock->getResultByShop($orderNo);

		foreach($tmp as $k => $v){
			if($v['result']){
				$handList[] = $v;
			}else{
				$list[] = $v;
			}
		}

		$this->view->jobList = $handList;
		$this->view->unhandList = $list;
		
		if(isset($_POST['submit'])){
			$passwordCheck = $staffDetail->checkPasswordCorrect(Model_EncryptHelper::hashsha(trim($_POST['password'])));
			if($passwordCheck){
			
				foreach ($_POST['check'] as $k => $v){
					if($v != 4){
						$pStock->updateResult($k, $passwordCheck['id'], $v, Model_DatetimeHelper::dateToday());
					}else{
						$pStock->updateResult($k, $passwordCheck['id'], $v, Model_DatetimeHelper::dateToday(),null,$_POST['other'][$k]);
					}
				}
			}else{
				$this->view->errorflag = true;
				$this->view->errorMessage = "Wrong Password";
				return false;
			}
			$url = "/repairparts/phone-stock-take/shop/".$shopHead;
			$this->_redirect($url);
		}
	}
	
	public function phoneStockSummaryAction(){
		$repaircenter = unserialize(ARR_RCENTER_MAPPING);
		
		$date = $this->_getParam('date');

		$staffDetail = new Model_DbTable_Roster_Stafflogindetail();
		$pStock = new Model_DbTable_Phonestocktake();
		
		$thisMonday = Model_DatetimeHelper::getThisWeekMonday();
		
		if(isset($_POST['sub_date'])){
			$url = "/repairparts/phone-stock-summary/date/".$_POST['chooseDate'];
			$this->_redirect($url);
		}
		
		if(empty($date)){
			$jobList = $pStock->listOrderByDate($thisMonday);
			$this->view->date = $thisMonday;
		}else{
			$jobList = $pStock->listOrderByDate($date);
			$this->view->date =$date;		
		}
		
		
		$this->view->jobList = $jobList;
		
		if(isset($_POST['submit'])){
			$password = $staffDetail->checkPasswordCorrect(Model_EncryptHelper::hashsha(trim($_POST['password'])));
			if($password){
			
				foreach ($_POST['confirm'] as $k => $v){
					if(!empty($_POST['reason'][$k])){
						$pStock->updateConfirm($k, Model_DatetimeHelper::dateToday(),1,$_POST['reason'][$k]);
					}else{
						$pStock->updateConfirm($k, Model_DatetimeHelper::dateToday(),1);
					}
				
				}
				
				$url = "/repairparts/phone-stock-summary";
				$this->_redirect($url);
			}else{
				$this->view->errorflag = true;
				$this->view->errorMessage = "Wrong Password";
				return false;
			}
		}
	}
	
	
	/**
	 * This function NEVER been used however it is necessary 
	 */
	public function transferBackAction(){
		
	}
	
	/**
	 * This function is for warehouse to do the adjustment 
	 * 
	 */
	public function shopAdjustInAction(){
		
		$idShop = $this->_getParam('shop');		
		$this->view->erorMessage = "";
			
		if($idShop==""){
		
			$this->view->errorMessage = "ERROR OCCUR, DO NOT PROCEEDE";
		}
		
		else{
			$this->view->idShop = $idShop;				
		}
		$rProduct = new Model_DbTable_Pr_Prproducts();
			
		$this->view->pList = $pList = $rProduct->listAllProducts();
		
		
	}
	/**
	 * This is the actual page to save the adjustment 
	 */
	
	public function saveShopAdjustInAction(){
		
		//adjust stock 
		//record the stock to AR
		//record how many adjusted 
		
		$rProducts = new Model_DbTable_Pr_Prproducts();
		$rStock = new Model_DbTable_Pr_Prstock();
		$rMove = new Model_DbTable_Pr_Prstockmovement();
		$productCode = "";
		$productQty = 0;
		$this->view->idShop = 0;
		$dateTody = Model_DatetimeHelper::dateToday("");
		$timeNow = Model_DatetimeHelper::timeNow("");
		$aINo = "AD".$dateTody.$timeNow;
		
		if($_POST){
		
		
			$this->view->idShop = $_POST['id_shop'];
		
			foreach($_POST['upload'] as $key => $value){
					
				$productCode = "";
				$productQty = 0;
					
				$arrtmp = explode("[",$value);

				$productCode = $arrtmp[0];
				$qty = (int)trim(str_replace("]","",$arrtmp[1]));
					
				//It should be in the Database
					
				if(!$rProducts->ifExist($productCode)){
		
					echo "ERROR OCCUR,DATA NOT SAVE,This Code Not Exist AT All:".$productCode;
				}
				else{
					//item already EXIST
					$idProduct = $rProducts->getProductID($productCode);
		
					//shop stock -
					$rStock->increaseStockShop($idProduct,$qty,$_POST['id_shop']);
					//record movement
					if($qty >0){
						$rMove->addMovement(5, $idProduct, $qty,$_POST['staff_name'],$_POST['id_shop'],$aINo,$_POST['move_reason']);
					}
					else{
						$rMove->addMovement(6, $idProduct, 0 - $qty,$_POST['staff_name'],$_POST['id_shop'],$aINo,$_POST['move_reason']);
					}
					$tmpStock = $rStock->getShopStock($idProduct,$_POST['id_shop']);
					$rMove->addMovement(9, $idProduct, $tmpStock,$_POST['staff_name'],$_POST['id_shop'],$aINo,$_POST['move_reason']);
					
				}
					
			}
		
		
		}	
		
		$this->view->AINO = $aINo;
		
		
		
		
	}
	
	
	/**
	 * This is the page enter from main page of repaire center 
	 * Parts faulty will not only create RMA record for warehouse 
	 * but also , it deduct the stock in shop stock 
	 * 
	 */
	public function shopFaultyProductAction(){
		
		$rProducts = new Model_DbTable_Pr_Prproducts();
		$sDetail = new Model_DbTable_Roster_Stafflogindetail();
		
		if(isset($_POST['go2'])){
		
		$codeFaultyProduct = $_POST['barcode_code'];
		$idShop = $_POST['id_shop'];
		$shopHead = $_POST['shop_head'];
		$desRow = $rProducts->getProductDes($codeFaultyProduct);
		
		
		$this->view->idShop = $idShop;
		$this->view->faultyBarcode = $codeFaultyProduct;
		$this->view->shopHead = $shopHead;
			if(!$desRow){
				$this->view->faulty_des = "<span style=\"color:red;\">Error Occur,BarCode Not Exist</span>";
			}
			else{
				$this->view->faulty_des =$desRow;
			}

		}

			
		
	}
	/**
	 * This is the actual page to record the faulty
	 */
	public function saveShopFoAction(){
		
		date_default_timezone_set("Australia/Melbourne");
		$sDetail = new Model_DbTable_Roster_Stafflogindetail();
		$monday = Model_DatetimeHelper::getThisWeekMonday();
		$this->view->dateToday = $dateToday = Model_DatetimeHelper::dateToday();
		$this->view->weekId = $weekId = date("W",strtotime($dateToday)) % 2;
		 
		$reason = new Model_DbTable_Faultyreason();
		$rProducts = new Model_DbTable_Pr_Prproducts();
		$fProduct = new Model_DbTable_Faultyproduct();
		
		
		
		$rStock = new Model_DbTable_Pr_Prstock();
		$rMove = new Model_DbTable_Pr_Prstockmovement();		
		$this->view->message = "";
		$this->view->shopHead = "";
		$rmareturn="";
		$staffName = "";
		
		
		if(isset($_POST['sub_upload'])){
			
			$stLine = $sDetail->checkPasswordCorrect(Model_EncryptHelper::hashsha(trim($_POST["staff_name"])));
			if(!$stLine){
				$this->view->errorFlag2 = true;
			
				$this->view->errorMessage = "The attendant password is wrong, please try again";
				
				return false;
			}
			else{
				if(!empty($stLine['ni'])){
					$staffName = $stLine['ni']."-".$stLine['id'];
					$this->view->staffName = $staffName;
				}else{
					$staffInfo = new Model_DbTable_Roster_Staffinfo();
					$staffDetail = $staffInfo->getStaffinfo($stLine['id']);
					$staffName = $staffDetail['first_name'].'.'.$staffDetail['last_name'];
					$this->view->staffName = $staffName;
				}
				
				if(!$rProducts->ifExist(trim($_POST['barcode_code']))){

					$this->view->errorFlag2 = true;
						
					$this->view->errorMessage = "ERROR OCCUR,DATA NOT SAVE,This Code Not Exist AT All:".$_POST['barcode_code'];
					
					return false;
				}
				else{
					
					if(trim($_POST['barcode_qty']) >0){
					//item already EXIST
					$idProduct = $rProducts->getProductID(trim($_POST['barcode_code']));
						
					//shop stock -
					$rStock->descreaseStockShop($idProduct,trim($_POST['barcode_qty']),$_POST['id_shop']);
				
					//record movement
					$rMove->addMovement(8, $idProduct,trim($_POST['barcode_qty']),$staffName,$_POST['id_shop'],$_POST['faulty_comment']);
				
				
					$productName = $rProducts->getProductDes(trim($_POST['barcode_code']));
				
					
							
						$neverUse =  (isset($_POST['never_use']))?1:0;
						//$rmareturn = $fProduct->addFaultyProduct(trim($_POST['barcode_code']), $productName, $_POST['shop_head'],$_POST['staff_name'],trim($_POST['barcode_qty']),40001,$_POST['faulty_comment'],"Parts Faulty","","");
							
						$fn = $fProduct->listAllUnhandledFaultyByShopByDate($_POST['shop_head'],$monday, $dateToday);
						$this->view->faultyNo = count($fn) + 1;
						$rmareturn = $fProduct->addRepairFaulty(trim($_POST['barcode_code']), $productName, $_POST['shop_head'],$staffName,trim($_POST['barcode_qty']),  $_POST['faulty_reason'], $_POST['faulty_comment'], "Parts Faulty","","", $_POST['staff_name_dis'],  $_POST['id_job'], $_POST['name_tech'], $neverUse);
							
						$reasonDes = $reason->getReasonDesByID($_POST['faulty_reason']);
							
							
							
						$this->view->message = "Faulty Saved,New RMA Created with RMA Number {$rmareturn} ,Return to Main Page";
							
					}
					else{

						$this->view->errorFlag2 = true;
						
						$this->view->errorMessage = "Faulty REVERSED,Please Notify Warehouse To Reject/Cancel this RMA ,Return to Main Page";
							
						return false;
							
					}
				
					$this->view->reasonName = $reasonDes;
					$this->view->faultId = $_POST['faulty_reason'];
					$this->view->pName = $productName;
					$this->view->rmaID = $rmareturn;
					$this->view->Comment = $_POST['faulty_comment'];
					$this->view->jobId = $_POST['id_job'];
					$this->view->shopHead = $_POST['shop_head'];
				}
			}
		
			
		
		}
		
	}
	
	public function warrantyFoAction(){
		date_default_timezone_set("Australia/Melbourne");
		$sDetail = new Model_DbTable_Roster_Stafflogindetail();
		$staffInfo = new Model_DbTable_Roster_Staffinfo();
		$monday = Model_DatetimeHelper::getThisWeekMonday();
		$shopLocation = new Model_DbTable_Shoplocation();
		$this->view->dateToday = $dateToday = Model_DatetimeHelper::dateToday();
		$this->view->weekId = $weekId = date("W",strtotime($dateToday)) % 2;
		$email = new Model_Emailshandler();
			
		$reason = new Model_DbTable_Faultyreason();
		$rProducts = new Model_DbTable_Pr_Prproducts();
		$fProduct = new Model_DbTable_Faultyproduct();
		$rJob = new Model_DbTable_Repairjob();
		
		
		
		$rStock = new Model_DbTable_Pr_Prstock();
		$rMove = new Model_DbTable_Pr_Prstockmovement();
		
		$this->view->message = "";
		$this->view->shopHead = "";
		$rmareturn="";
		$staffName = "";
		
		
		if(isset($_POST['sub_upload'])){
				
			$stLine = $sDetail->checkPasswordCorrect(Model_EncryptHelper::hashsha(trim($_POST["staff_name"])));
			if(!$stLine){
				$this->view->errorFlag2 = true;
					
				$this->view->errorMessage = "The attendant password is wrong, please try again";
		
				return false;
			}
			else{
				if($stLine['ni']!= null){
					$staffName = $stLine['ni'];
					$this->view->staffName = $staffName;
				}else{
					
					$staffDetail = $staffInfo->getStaffinfo($stLine['id']);
					$staffName = $staffDetail['first_name'].'.'.$staffDetail['last_name'];
					$this->view->staffName = $staffName;
				}
		
				if(!$rProducts->ifExist(trim($_POST['barcode_code']))){
		
					$this->view->message = "<span style=\"color:#f00;\">ERROR OCCUR,DATA NOT SAVE</span>,This Code Not Exist AT All:".$_POST['barcode_code'];
				}else{
					//item already EXIST
					$idProduct = $rProducts->getProductID(trim($_POST['barcode_code']));
					
		
		
					$productName = $rProducts->getProductDes(trim($_POST['barcode_code']));
		
					if(trim($_POST['barcode_qty']) >0){
							
							
						$fn = $fProduct->listAllUnhandledFaultyByShopByDate($_POST['shop_head'],$monday, $dateToday);
						$this->view->faultyNo = count($fn) + 1;

						$reasonDes = "Return By Customer (Warranty Part)";
						//shop stock -
						$rStock->descreaseStockShop($idProduct,trim($_POST['barcode_qty']),$_POST['id_shop']);
						
						//record movement
						$rMove->addMovement(8, $idProduct,trim($_POST['barcode_qty']),$staffName,$_POST['id_shop'],$_POST['faulty_comment']);
						
						$rmareturn = $fProduct->addRepairFaulty(trim($_POST['barcode_code']), $productName, $_POST['shop_head'],$staffName,trim($_POST['barcode_qty']),  $_POST['faulty_reason'], $_POST['faulty_comment'], "Parts Faulty","","", $_POST['staff_name_dis'],  $_POST['id_job'], $_POST['name_tech'], 0);
	
						if($_POST['out_warranty'] == 1){
							$rJob->updateWarrantyCheck($_POST['id_job'], 'outwarranty');
							$shopEmail = $shopLocation->getNameByHead($_POST['shop_head']);
							$email->sendActionEmail("eco3@phonecollection.com.au", "Please confirm Job warranty", "Hi Manager<br/><br/> Job ID:".$_POST['id_job']." is out of warranty, but staff: ".$staffName." still deceide do the service for customer on ".$dateToday." , please confirm whether you approve this service.<br/><br/>"."Check Job Detail<br/>http://".WEB_IP."/repaircenter/viewdetail/jobid/".$_POST['id_job']."<br/><br/>Please use the link as below.<br/><br/>http://".WEB_IP."/repaircenter/warranty-confirm/");
							if(!empty($shopEmail['shop_manager_email'])){
								$email->sendActionEmail($shopEmail['shop_manager_email'], "Please confirm Job warranty", "Hi Manager<br/><br/> Job ID:".$_POST['id_job']." is out of warranty, but staff ".$staffName." still deceide do the service for customer on ".$dateToday." , please confirm whether you approve this service.<br/><br/>"."Check Job Detail<br/>http://".WEB_IP."/repaircenter/viewdetail/jobid/".$_POST['id_job']."<br/><br/>Please use the link as below.<br/><br/>http://".WEB_IP."/repaircenter/warranty-confirm/");
							}

						}
						$rJob->updateWarrantyStaff($_POST['id_job'], $stLine['id']);
						
						$this->view->message = "Faulty Saved,New RMA Created with RMA Number {$rmareturn} ,Return to Main Page";
							
					}
					else{
							
						$this->view->message = "Faulty REVERSED,Please Notify Warehouse To Reject/Cancel this RMA ,Return to Main Page";
							
					}
		
					$this->view->reasonName = $reasonDes;
					$this->view->faultId = $_POST['faulty_reason'];
					$this->view->pName = $productName;
					$this->view->rmaID = $rmareturn;
					$this->view->Comment = $_POST['faulty_comment'];
					$this->view->jobId = $_POST['id_job'];
					$this->view->shopHead = $_POST['shop_head'];
				}
			}
		
				
		
		}
	}
	
	/**
	 * Shop parts summary function has multi views
	 * 1. this is the page for shop to check the parts used for selected days
	 * it also show the parts has been used for what job 
	 * if the discount is ok 
	 * if the parts has been returned 
	 * 2.if the "custpart" param is exist it show which customer parts has been return to warehouse 
	 * this is for when the  driver come to pickup 
	 */
	public function shopPartsSummaryAction(){
		date_default_timezone_set('Australia/Melbourne');
		
		$idShop = $this->_getParam('shop');
		$showCust = $this->_getParam("custpart");
		
		$this->view->shopName = self::$rCenterMappRev[$idShop];
		
		$dateBegin = "";
		$dateEnd = "";
		
		$thisMonday = Model_DatetimeHelper::getThisWeekMonday();
		$thisSunday = Model_DatetimeHelper::getThisWeekSunday();
		$lastSunday = Model_DatetimeHelper::getLastWeekSunday();
		$lastMonday = Model_DatetimeHelper::getLastWeekMonday();
		
		$dB = $this->_getParam("date_begin");
		$dE = $this->_getParam("date_end");
		if($dB!=""){
			
			$lastMonday = $dB;
		}
		if($dE!=""){
			$lastSunday = $dE;
		}
		
		
		
		$rMove = new Model_DbTable_Pr_Prstockmovement();
		
		//used 
		if($_POST){
			$this->view->pUsed = $rMove->getStockMoveByDateByCode(2, $_POST["date_begin"],$_POST["date_end"],$idShop);
			
			//Error Correction
			$this->view->pErr = $rMove->getStockMoveSumByDateByCode(7, $_POST["date_begin"],$_POST["date_end"],$idShop);
			
			//Faulty
			
			$this->view->pFau = $rMove->getStockMoveSumByDateByCode(8, $_POST["date_begin"],$_POST["date_end"],$idShop);			
			
			$this->view->dateBegin = $_POST["date_begin"];
			$this->view->dateEnd = $_POST["date_end"];
			
			//get files
			//echo "Read File";
			$slFolder = SALES_LINE_FOLDER;
				
			$lastMondayFile = Model_DatetimeHelper::getMondayByDate($_POST["date_begin"],"");
				
			$salesOldFileName = "SALESLINEOLD".$lastMondayFile;
			$salesNewFileName = "SALESLINENEW".$lastMondayFile;
			
				
			if(file_exists(getcwd()."/".$slFolder."/".$salesOldFileName) && file_exists(getcwd()."/".$slFolder."/".$salesNewFileName) ){
			
				$tmpArray = array();
				$fl = fopen(getcwd()."/".$slFolder."/".$salesOldFileName,"r");
			
				while (($lineData = fgetcsv($fl)) != false){
					
					$tmpArray[] = $lineData[5]; // location
					$tmpArray[] = $lineData[8]; //invoice
					//$tmpArray[] = $lineData[9]; //date
					$tmpArray[] = $lineData[17]; // act money
					$tmpArray[] = $lineData[0];//barcode
					$tmpArray[] = $lineData[2]; //des
					
				}
				fclose($fl);
				$fl = fopen(getcwd()."/".$slFolder."/".$salesNewFileName,"r");
			
				while (($lineData = fgetcsv($fl)) != false){
					
					$tmpArray[] = $lineData[5]; // location
					$tmpArray[] = $lineData[8]; //invoice
					//$tmpArray[] = $lineData[9]; //date
					$tmpArray[] = $lineData[17]; // act money
					$tmpArray[] = $lineData[0];//barcode
					$tmpArray[] = $lineData[2]; //des
					
				}
				fclose($fl);
				//var_dump($tmpArray);
				$this->view->fileArray = $tmpArray;
			}
			else{
			
				$this->view->fileArray = "";
			}
			
		}
		else{
		
		$this->view->pUsed = $rMove->getStockMoveByDateByCode(2, $lastMonday, $lastSunday,$idShop);
		
		//Error Correction 
		$this->view->pErr = $rMove->getStockMoveSumByDateByCode(7, $lastMonday, $lastSunday,$idShop);
		
		//Faulty
		
		$this->view->pFau = $rMove->getStockMoveSumByDateByCode(8, $lastMonday, $lastSunday,$idShop);

			$this->view->dateBegin = $lastMonday;
			$this->view->dateEnd = $lastSunday;
			
		//get files
			//echo "Read File";
			$slFolder = SALES_LINE_FOLDER;
			
			$lastMondayFile = Model_DatetimeHelper::getLastWeekMonday("");
			
			$salesOldFileName = "SALESLINEOLD".$lastMondayFile;
			$salesNewFileName = "SALESLINENEW".$lastMondayFile;

			
			if(file_exists(getcwd()."/".$slFolder."/".$salesOldFileName) && file_exists(getcwd()."/".$slFolder."/".$salesNewFileName) ){
				
				$tmpArray = array();
				$fl = fopen(getcwd()."/".$slFolder."/".$salesOldFileName,"r");
				
				while (($lineData = fgetcsv($fl)) != false){
					$tmpArray[] = $lineData[5]; // location
					$tmpArray[] = $lineData[8]; //invoice
					//$tmpArray[] = $lineData[9]; //date
					//$tmpArray[] = $lineData[17]; // act money
					$tmpArray[] = $lineData[0];//barcode
					$tmpArray[] = $lineData[2]; //des
				}
				fclose($fl);
				$fl = fopen(getcwd()."/".$slFolder."/".$salesNewFileName,"r");
				
				while (($lineData = fgetcsv($fl)) != false){
					$tmpArray[] = $lineData[5]; // location
					$tmpArray[] = $lineData[8]; //invoice
					//$tmpArray[] = $lineData[9]; //date
				    //$tmpArray[] = $lineData[17]; // act money
					$tmpArray[] = $lineData[0];//barcode
					$tmpArray[] = $lineData[2]; //des
				}
				fclose($fl);				
				
				$this->view->fileArray = $tmpArray;
			}
			else{
				
				$this->view->fileArray = "";
			}
					
		}
		
		$this->view->idShop = $idShop;
		
		if($showCust == "yes"){
			
			if($idShop == 5){
				$this->renderScript( 'repairparts/return-customer-part-glassonly.phtml' );
			}
			else{
				$this->renderScript( 'repairparts/return-customer-part.phtml' );
			}
				
			
		}
		
		
	}
	
	/**
	 * this function is to check new barcode within 2 days
	 * I don't know what it is for 
	 */
	
	public function newBarcodeAction(){
		//new barcode in 2 days
		
		$twoDaysAgo = date("Y-m-d",strtotime("-1 day",strtotime("yesterday")));
		echo $twoDaysAgo;
		
		$rProducts = new Model_DbTable_Pr_Prproducts();
		$newProductList = $rProducts->listNewProducts($twoDaysAgo);
				
		$this->view->newProductList = $newProductList;
		
	
	}
	
	/**
	 * This is for warehouse check the all movement of the parts 
	 * it will list all the history of the part in all shops 
	 * this function is only available in warehouse 
	 */
	public function partMoveHistoryAction(){
		
		$rProducts = new Model_DbTable_Pr_Prproducts();
		$rMove = new Model_DbTable_Pr_Prstockmovement();
		$this->view->list = "";
			if($_GET){
			$idProduct = $rProducts->getProductID($_GET['part_code']);		
			$this->view->list = $rMove->getProductMove($idProduct);
			}
		
	}
	/**
	 * This function is warehouse / shop check the moment of the part in the select shop
	 * it ONLY shows the movement history for that shop 
	 */
	public function partMoveHistoryShopAction(){
		
		$shopCode = $this->_getParam("shop");
		
		$rProducts = new Model_DbTable_Pr_Prproducts();
		$rMove = new Model_DbTable_Pr_Prstockmovement();
		$this->view->list = "";
		if($_GET){
			$idProduct = $rProducts->getProductID($_GET['part_code']);
			$this->view->list = $rMove->getProductMove($idProduct,$shopCode);
		}		
		
		$this->view->shopCode = $shopCode;
	}
	
	/**
	 * This is once off function to check if they parts they recorded is correct
	 */
	public function ZNOUSEpartMoveHistorySummaryAction(){
		set_time_limit(0);

		$shopCode = $this->_getParam("shop");
		
		$dateBegin = $this->_getParam("date_begin");
		$dateEnd = $this->_getParam("date_end");
		
		$timeBegin = $this->_getParam("time_begin");
		$timeEnd = $this->_getParam("time_end");
		
		$this->view->showDetail = $this->_getParam("show_detail");
		
		$rProducts = new Model_DbTable_Pr_Prproducts();
		$rStock = new Model_DbTable_Pr_Prstock();
		$rMove = new Model_DbTable_Pr_Prstockmovement();


		$rPList = $rProducts->listAllProducts();
		
		$arrRes = array();
		$arrPrice = array();
		$arrStockGo = array();
		
		foreach($rPList as $key => $v){

			$tmpArr = array();
			$tmpArr["id_product"] = $v["id_product"];
			$tmpArr["code_product"] = $v["code_product"];
			$tmpArr["title_product"] =  $v["title_product"];
			$tmpArr["price_a"] = $v["price_a"];
			$arrPrice[] = $v["price_a"];
			
			$tmpArr["stock"] = $rStock->getShopStock($v["id_product"], $shopCode);
			
			// ti
			$tiList = $rMove->getProductMoveByDateTimeByCode(3,$v["id_product"], $dateBegin, $dateEnd,$shopCode,$timeBegin,$timeEnd);
			
			$strDetailTi ="";
			$qtyTi = 0;
			
			if(!empty($tiList)){
			foreach($tiList as $k2 => $v2){
				
				if($v2['qty_product']!=0){
				$strDetailTi .= "{$v2['date_move']} {$v2['time_move']} -  {$v2['id_job']} x {$v2['qty_product']} <br />";
				$qtyTi +=  	$v2['qty_product'];
				}
			}
			}
			$tmpArr["detail_ti"] = $strDetailTi;
			$tmpArr["qty_ti"] = $qtyTi;
			
			
			// to 
			$toList = $rMove->getProductMoveByDateByCode(4,$v["id_product"], $dateBegin, $dateEnd,$shopCode,$timeBegin,$timeEnd);
				
			$strDetailTo ="";
			$qtyTo = 0;
				
			if(!empty($toList)){
				foreach($toList as $k21 => $v21){
					$strDetailTo .= "{$v21['date_move']} {$v21['time_move']} -  {$v21['id_job']} x {$v21['qty_product']} <br />";
					$qtyTo +=  	$v21['qty_product'];
				}
			}
			$tmpArr["detail_to"] = $strDetailTo;
			$tmpArr["qty_to"] =  0 - $qtyTo;
			
			// go
			$goList = $rMove->getProductMoveByDateByCode(2,$v["id_product"], $dateBegin, $dateEnd,$shopCode,$timeBegin,$timeEnd);
				
			$strDetailGo ="";
			$qtyGo = 0;
				
			if(!empty($goList)){
				foreach($goList as $k22 => $v22){
					$strDetailGo .= "{$v22['date_move']} {$v22['time_move']} -  {$v22['id_job']} x {$v22['qty_product']} <br />";
					$qtyGo +=  	$v22['qty_product'];
				}
			}
			$tmpArr["detail_go"] = $strDetailGo;
			$tmpArr["qty_go"] = 0 - $qtyGo;
			$arrStockGo[] = $qtyGo;
			//ei
			$eiList = $rMove->getProductMoveByDateByCode(7,$v["id_product"], $dateBegin, $dateEnd,$shopCode,$timeBegin,$timeEnd);
				
			$strDetailEi ="";
			$qtyEi = 0;
				
			if(!empty($eiList)){
				foreach($eiList as $k23 => $v23){
					$strDetailEi .= "{$v23['date_move']} {$v23['time_move']} -  {$v23['id_job']} x {$v23['qty_product']} <br />";
					$qtyEi +=  	$v23['qty_product'];
				}
			}
			$tmpArr["detail_ei"] = $strDetailEi;
			$tmpArr["qty_ei"] = $qtyEi;
			
			// fo
			$foList = $rMove->getProductMoveByDateByCode(8,$v["id_product"], $dateBegin, $dateEnd,$shopCode,$timeBegin,$timeEnd);
				
			$strDetailFo ="";
			$qtyFo = 0;
				
			if(!empty($foList)){
				foreach($foList as $k24 => $v24){
					$strDetailFo .= "{$v24['date_move']} {$v24['time_move']} -  {$v24['id_job']} x {$v24['qty_product']} <br />";
					$qtyFo +=  	$v24['qty_product'];
				}
			}
			$tmpArr["detail_fo"] = $strDetailFo;
			$tmpArr["qty_fo"] = 0 - $qtyFo;
			
			// AI
			$aiList = $rMove->getProductMoveByDateByCode(5,$v["id_product"], $dateBegin, $dateEnd,$shopCode,$timeBegin,$timeEnd);
				
			$strDetailAi ="";
			$qtyAi = 0;
				
			if(!empty($aiList)){
				foreach($aiList as $k25 => $v25){
					$strDetailAi .= "{$v25['date_move']} {$v25['time_move']} -  {$v25['id_job']} x {$v25['qty_product']} <br />";
					$qtyAi +=  	$v25['qty_product'];
				}
			}
			$tmpArr["detail_ai"] = $strDetailAi;
			$tmpArr["qty_ai"] = $qtyAi;
						
			//AO
			
			$aoList = $rMove->getProductMoveByDateByCode(6,$v["id_product"], $dateBegin, $dateEnd,$shopCode,$timeBegin,$timeEnd);
			
			$strDetailAo ="";
			$qtyAo = 0;
			
			if(!empty($aoList)){
				foreach($aoList as $k26 => $v26){
					$strDetailAo .= "{$v26['date_move']} {$v26['time_move']} -  {$v26['id_job']} x {$v26['qty_product']} <br />";
					$qtyAo +=  	$v26['qty_product'];
				}
			}
			$tmpArr["detail_ao"] = $strDetailAo;
			$tmpArr["qty_ao"] = 0 - $qtyAo;
			
			$tmpArr["move_total"] = $qtyTi	- $qtyTo + $qtyEi - $qtyFo - $qtyGo + $qtyAi - $qtyAo;

			$tmpArr ["org_stock"] = $tmpArr["stock"] - $tmpArr["move_total"];
			
			$arrRes[] = $tmpArr;
		}
		
		array_multisort($arrPrice,SORT_DESC,$arrStockGo,SORT_ASC,$arrRes);
		$this->view->arrRes = $arrRes;
		
		//var_dump($arrRes);
		
	}
	
	// shop to shop transfer function has been disabled 
	
	
	/**
	 * List all RGN (Good Receive)
	 */
	public function checkRgnMainAction(){
		
		$rgn = new Model_DbTable_Pr_Stockmove_Rgn();
		$res = $rgn->listAllDistinct();
		$this->view->resList = $res;
	}
	/**
	 * list all RKT (Shop transfer TI)
	 */
	public function checkRktMainAction(){
	
		$rgn = new Model_DbTable_Pr_Stockmove_Rkt();
		$res = $rgn->listAllDistinct();
		$this->view->resList = $res;
	}
	/**
	 * Rks funcon is only for shop alex when we sales the 
	 * parts instead of sending 
	 */
	public function checkRksMainAction(){
	
		$rgn = new Model_DbTable_Pr_Stockmove_Rks();
		$res = $rgn->listAllDistinct();
		$this->view->resList = $res;
	}
	
	/**
	 * check all Adjust of the parts
	 */
	public function checkAdMainAction(){
	
		$rgn = new Model_DbTable_Pr_Stockmove_Ad();
		$res = $rgn->listAllDistinct();
		$this->view->resList = $res;
	}	

	/**
	 * Check all shop to shop transfer 
	 */
	public function checkStsMainAction(){
		$rgn = new Model_DbTable_Pr_Stockmove_Sts();
		$res = $rgn->listAllDistinct();
		$this->view->resList = $res;		
		
		
	}
	
	/**
	 * For all RGN KT KS AD , it all using this function to check the details
	 * 
	 */
	public function checkNotesDetailAction(){
		
		$idJob = $this->_getParam("idjob");
		$skMove = new Model_DbTable_Pr_Prstockmovement();
		$this->view->resList = $skMove->listByNoteId($idJob);
		$this->view->idJob = $idJob;
		//var_dump($this->view->resList);
	
	}
	
	/**
	 * Check STS note (shop to shop transfer) only for shop 3
	 * 
	 */
	public function checkNotesDetailStsAction(){
	
		$idJob = $this->_getParam("idjob");
		$skMove = new Model_DbTable_Pr_Prstockmovement();
		$this->view->resList = $skMove->listByNoteId($idJob);
		$this->view->idJob = $idJob;
		//var_dump($this->view->resList);
	
	}
	
	/**
	 * This functon run on 126 
	 * this function is request carla to calculate the staff bonus 
	 * this Page is no longer in use , leo already write the new one 
	 */
	public function listStaffSummaryAction(){

		$dateBegin = $this->_getParam("date_begin");
		$dateEnd = $this->_getParam("date_end");
		//var_dump($dateBegin);
		$arrRes = array();
		$arrStaff = array();
		$arrShop = array();
		$arrDate = array();
		$invPro = "";
		
		$rJobs = new Model_DbTable_Repairjob(Zend_Registry::get('db_remoteapp'));
		
		$rMove = new Model_DbTable_Pr_Prstockmovement(Zend_Registry::get('db_remoteapp'));
		$rPart = new Model_DbTable_Pr_Prproducts(Zend_Registry::get('db_remoteapp'));
		
		$rStatus = new Model_DbTable_Repairstatusrecord(Zend_Registry::get('db_remoteapp'));
		
		$jList = $rJobs->listAllFinishedJobsByDate($dateBegin, $dateEnd);
		//echo "<pre>";
		foreach($jList as $job){
			$stJob = $rStatus->getLastStatus($job["id_job"]);
			
			if($stJob[0]["id_status"] == 90 ){
				
				$shop =  strtoupper(trim($job["shop_code"]));
				
				$invPro = "";
				if($shop == 'WHAL'){
					$invPro = Model_Aposinit::initAposInvPro('FGIC');
				}else{
					$invPro = Model_Aposinit::initAposInvPro($shop);
				}
				if($invPro == ""){
					dd($shop);
				}
				
				$invLine = "";
				$invLine2 = "";
				$inv1Count = "";
				$inv2Count = "";
				
				$inv1Disc = 0;
				$inv2Disc = 0;
				
				
				$inv1 = substr($job["invoice_no"],-8);
				$inv2 = "";
				
				$invLine = $invPro->getRepairInvoice("L1".$inv1);
				
				$inv1Count = count($invPro->getInvoiceProducts("L1".$inv1));

				$inv1Disc = $invPro->getInvoiceDiscount("L1".$inv1);
				
				if(strlen($job["invoice_no2"]) > 0){

					$inv2 = substr($job["invoice_no2"],-8);
					$invLine2 = $invPro->getRepairInvoice("L1".$inv2); 					
					$inv2Count = count($invPro->getInvoiceProducts("L1".$inv2));
					$inv2Disc = $invPro->getInvoiceDiscount("L1".$inv2); 
				}
		
				//get repair parts 

				$partsRes = $rMove->getPartsSummaryByJobId($job['id_job'],"price_b");
				//d($partsRes);
				//var_dump($tmprows);
				// bonus summary
				$wBonus = false;
				$maxBonusFull = 0;
				$maxBonusHalf = 0;
				
				$amtBonusPartsAmt = 1;
				$amtBonusParts = 0;
				$amtBonusService = 0;//2014-07-11
				
				
				foreach($partsRes[0] as $part){
					$amtBonusParts += $amtBonusPartsAmt * $part[1];
					$amtBonusService += $amtBonusPartsAmt * $part[1];//2014-07-11
					$id = $rPart->getProductID($part[0]);
					$row = $rPart->getProduct($id);
					if($row['w_bonus']){
						$wBonus = true;
						if($row["amt_full_bonus"] > $maxBonusFull){
							$maxBonusFull = $row["amt_full_bonus"]; 
							$maxBonusHalf = $row["amt_dis_bonus"];
						}
					}
				}
				
				$amtBonus = "N/A";

				
				$repairDis = 0;
				$salesDis = 0;
				
				if($wBonus){
					
					if($job["invoice_no2"] == "" ){
						
						if($inv1Count==1){
							$repairDis = $partsRes[1] - $invLine;
						}
						if($inv1Count>1){
							$repairDis = $partsRes[1] - $invLine;
							$salesDis = $inv1Disc;
						}	
					}
					
					else{
						
						if($inv1==$inv2){
							
							if($inv1Count==1){
								$repairDis = $partsRes[1] - $invLine;
							}
							if($inv1Count>1){
								$repairDis = $partsRes[1] - $invLine;
								$salesDis = $inv1Disc;
							}
						}						
							else{

							$repairDis = $partsRes[1] - $invLine - $invLine2;
							$salesDis = $inv1Disc + $inv2Disc;
						}	
							
						}					
					
				}else{
					$amtBonusParts = 0;
					$amtBonusService = 0;
				}
				
				$bonusAmt = 0;
				
				if( ($repairDis + $salesDis) >0){
					
					$amtBonusParts = 0;
				}
				
				
				if($wBonus){
				if( ($repairDis < 5 && $salesDis < 5) || ($repairDis + $salesDis) < 5  ){
					
					$bonusAmt = $maxBonusFull;
					$maxBonusHalf = 0;
					
				}
				
				if(($repairDis >= 5 && $repairDis < 10 && $salesDis >= 5 && $salesDis < 10 ) || (($repairDis + $salesDis) >= 5 && ($repairDis + $salesDis) < 10)  ){
					$bonusAmt = $maxBonusHalf;
					$maxBonusFull = 0;
				}
				if(($repairDis + $salesDis) > 10){
					
					$bonusAmt = 0;
					
					$maxBonusHalf = 0;
					$maxBonusFull = 0;
					
					
				}
				
				$policyArray = $rJobs->bonusRule($job["id_job"]);

				if(!$policyArray[0] || !$policyArray[1] ||$job['fix_by_hq']==1){
					$bonusAmt = 0;
					$amtBonusParts = 0;
					$amtBonusService = 0;
				}
				}
				//WHo , what ,finish time , quote , invoices , who record 
				$tmpArr = array();
				
				$tmpArr["id_job"] = $job["id_job"];
				$tmpArr["date_start"] =  $job["date_start"];
				$tmpArr["repair_staff"] = $job["repair_staff"];
				
				$arrStaff[] =  $job["repair_staff"];
				
				$tmpArr["shop_code"] = $job["shop_code"];
				
				$arrShop[] = $job["shop_code"]; 
				
				$tmpArr["mobile_model"] = $job["mobile_model"];
				$tmpArr["quot_price"] = $job["quot_price"];
				$tmpArr["invoice_no"] = $job["invoice_no"];
				$tmpArr["invoice_qty"] =  $inv1Count;
				$tmpArr["invoice_amt"] = $invLine;
				$tmpArr["invoice_no2"] = $job["invoice_no2"];
				$tmpArr["invoice_qty2"] = $inv2Count;
				$tmpArr["invoice_dis"] = $inv1Disc;
				$tmpArr["invoice_dis2"] = $inv2Disc;
				$tmpArr["invoice_amt2"] = $invLine2;
				$tmpArr["staff_record"] = $job["staff_record"];
				$tmpArr["time_record"] = $job["time_record"];
				$tmpArr["part_sum"] = $partsRes;
				$tmpArr["w_bonus"] = $wBonus;
				$tmpArr["repair_disc"] = $repairDis;
				$tmpArr["sales_disc"] = $salesDis;
				$tmpArr["bonus_amt"] = $bonusAmt;
				$tmpArr["full_bonus_amt"] = $maxBonusFull;
				$tmpArr["dis_bonus_amt"] = $maxBonusHalf;
				$tmpArr["fix_by_hq"] = $job['fix_by_hq'];
				
				
				$arrDate[] = $job["time_record"];
				
				$tmpArr['bonus_rule'] = $rJobs->bonusRule($job["id_job"]);
				$tmpArr['bonus_part'] = $amtBonusParts;
				$tmpArr['bonus_service'] = $amtBonusService;
				 
				$arrRes[] = $tmpArr;
			}	
		}
		
		//array_multisort($arrStaff,SORT_ASC,$arrShop,SORT_ASC,$arrDate,SORT_ASC,$arrRes);
		array_multisort($arrShop,SORT_ASC,$arrStaff,SORT_ASC,$arrDate,SORT_ASC,$arrRes);
		//var_dump($arrRes);
		//echo "</pre>";
		$this->view->arrRes = $arrRes;
		//d($arrRes);
		$this->renderScript('/repairparts/list-staff-summary-toreplace.phtml');
	}
	
	
	/**
	 * This function is for warehouse to order repair parts 
	 * this function is duplicated with other funcion 
	 * it shows all the TI GO and FO according the stock in warehouse give recommendation of ordering 
	 */
	
	public function lastWeekMovementAction(){

		
		$dateBegin = Model_DatetimeHelper::getLastWeekMonday();
		$dateEnd = Model_DatetimeHelper::getLastWeekSunday();
		
		$recDateBegin = $this->_getParam("date_begin");
		$recDateEnd = $this->_getParam("date_end");
		
		if($recDateBegin != ""){
			$dateBegin = $recDateBegin;
			$dateEnd = $recDateEnd;
		}
		
		$rProducts = new Model_DbTable_Pr_Prproducts();
		$rMove = new Model_DbTable_Pr_Prstockmovement();
		$rStock = new Model_DbTable_Pr_Prstock();
		
		$rPlist = $rProducts->listAllProducts();
		$arrRes = array();
		
		foreach($rPlist as $key => $v){
			
			$idProduct = $v["id_product"];
			
			$tiSum = $rMove->getProductMoveSummaryByDateByCode(3, $idProduct, $dateBegin, $dateEnd);
			$goSum = $rMove->getProductMoveSummaryByDateByCode(2, $idProduct, $dateBegin, $dateEnd); 
			$foSum = $rMove->getProductMoveSummaryByDateByCode(8, $idProduct, $dateBegin, $dateEnd);
			$whStock = $rStock->getWarehouseStock($idProduct);
			
			if($tiSum[0]['sum_qty'] > 0 || $goSum[0]['sum_qty'] > 0 || $foSum[0]['sum_qty'] > 0){
				$tmpArr = array();
				$tmpArr[] = $idProduct;
				$tmpArr[] = $v["code_product"];
				$tmpArr[] = $v["title_product"];
				$tmpArr[] = $tiSum[0]['sum_qty'];
				$tmpArr[] = $goSum[0]['sum_qty'];
				$tmpArr[] = $foSum[0]['sum_qty'];
				$tmpArr[] = $whStock;
				
				$lno = ( $tiSum[0]['sum_qty'] > $goSum[0]['sum_qty'] )?$tiSum[0]['sum_qty']:$goSum[0]['sum_qty'];
				
				if($whStock < $lno * 2){
					if($lno *2 - $whStock > 10){
						$tmpArr[] = 5 * round(($lno *2 - $whStock)/ 5); 
					}
					else{
						
						$tmpArr[] = ($lno *2 - $whStock);
					}	
				}
				else{
					$tmpArr[] = 0;
				}

				if($v["code_product"]!="SERVICE" && $v["code_product"]!="CUSTPART" ){
				
					$arrRes[] = $tmpArr;
				}
			
			}
			
		}
		
		//loop all the parts 
		$arrOrder = array();
		
		foreach($arrRes as $k2 => $v2){
			$arrOrder[$k2] = $v2[7];
		}
		
		array_multisort($arrOrder,SORT_DESC,$arrRes);
		
		$this->view->arrRes = $arrRes;
		//var_dump($arrRes);
		
		
		
	}
	
	/**
	 * this is another summary which did not been use very good 
	 * it show the part been in which shop and total onhand of shop and warehouse 
	 * if the part is LCD or not and total sales and tranfer 
	 * 
	 */
	public function partAnalysisSummaryAction(){
		
		set_time_limit(0);
		
		$dateEnd = Model_DatetimeHelper::dateYesterday();
		$dateBegin = Model_DatetimeHelper::adjustWeeks("sub", $dateEnd, 4);
		
		$rProducts = new Model_DbTable_Pr_Prproducts();
		$rMove = new Model_DbTable_Pr_Prstockmovement();
		$rStock = new Model_DbTable_Pr_Prstock();
		
		$rPlist = $rProducts->listAllProducts();
		
		$arrRes = array();	
		$arrParts = array();
		
		foreach(self::$rCenterMappRev as $key => $v){
			$idShop = $key;
			
			foreach($rPlist as $k => $v){
				$idProduct = $v["id_product"];
				
				$goSum = $rMove->getProductMoveSummaryByDateByCode(2, $idProduct, $dateBegin, $dateEnd,$idShop);
				$foSum = $rMove->getProductMoveSummaryByDateByCode(8, $idProduct, $dateBegin, $dateEnd,$idShop);
				$tiSum = $rMove->getProductMoveSummaryByDateByCode(3, $idProduct, $dateBegin, $dateEnd,$idShop);
				$goAll = $rMove->getProductMoveSummaryByDateByCode(2, $idProduct, $dateBegin, $dateEnd);				

				$shopStock = $rStock->getShopStock($idProduct, $idShop);
				$whStock = $rStock->getWarehouseStock($idProduct);
				
				
				if($shopStock>0 && $foSum[0]['sum_qty'] == 0 && $goSum[0]['sum_qty'] == 0 ){
					if($v["code_product"]!="SERVICE" && $v["code_product"]!="CUSTPART" && $v["code_product"]!="ERROR1"  ){
					
						if(array_search($idProduct,$arrParts)){
						// added into this part before 
							$arrRes[$idProduct][3] +=1;
							$arrRes[$idProduct][4] +=$shopStock;
						}
						else{
						//first time met this parts
						$arrParts[] = $idProduct;

						$tmpArr = array();
						$tmpArr[] = $idProduct;
						$tmpArr[] = $v["code_product"];
						$tmpArr[] = $v["title_product"];
						$tmpArr[] = 1;
						$tmpArr[] = $shopStock;
						$tmpArr[] = $whStock;
						$tmpArr[] = $v["is_lcd"];
						$tmpArr[] = $goAll[0]['sum_qty'];
						$tmpArr[] = $tiSum[0]['sum_qty'];
							
						$arrRes[$idProduct] = $tmpArr;
						
							
						}
					
					}
						
				}
				
			}
			
		}
		
		d($arrRes);
		
		$arrNoSaleShop = array();
		$arrOnhand = array();
		
		$arrResNew = array();
		foreach($arrRes as $k2 => $v2){
			
			$arrResNew[] = $v2;
			$arrNoSaleShop[] = $v2[3];
			$arrOnhand[] = $v2[4];
		}
		
		array_multisort($arrNoSaleShop,SORT_DESC,$arrOnhand,SORT_DESC,$arrResNew);
		
		
		$this->view->arrResNew = $arrResNew;
	}
	
	/**
	 * this function is not very important
	 * this function was for paper stock take and print barcode now is
	 */
	
	public function shopStockMainAction(){
	
		$idShop = $this->_getParam('shop');
	
		$prCate = new Model_DbTable_Pr_Category();
	
		$catList = $prCate->listCategory();
		$this->view->idShop = $idShop;
		$this->view->catList = $catList;
	
	}
	
	
	/**
	 * this function is not very important
	 * this function was for paper stock take and print barcode now is
	 */
	
	public function shopStockTakeAction(){
	
		$idShop = $this->_getParam('shop');
		$idCate = $this->_getParam('cate');
	
		$rProducts = new Model_DbTable_Pr_Prproducts();
	
		$this->view->idShop = $idShop;
		$this->view->idCate = $idCate;
	
		if($idCate == 'all'){
			$this->view->pList = $rProducts->listAllProducts();
		}else{
			$this->view->pList = $rProducts->listProductsByCate($idCate);
		}
	
	
		$this->view->dateToday = Model_DatetimeHelper::dateToday();
	
	}
	
	
	/**
	 * This function is in the repaircenter main page 
	 * it show the shop 4 weeks recent sold out and 4 weeks no sale which need to return 
	 */
	public function partsAnalysisAction(){
		
		$idShop = $this->_getParam("shop");
		
		$dateEnd = Model_DatetimeHelper::dateYesterday();
		$dateBegin = Model_DatetimeHelper::adjustWeeks("sub", $dateEnd, 4);
		
		$rProducts = new Model_DbTable_Pr_Prproducts();
		$rMove = new Model_DbTable_Pr_Prstockmovement();
		$rStock = new Model_DbTable_Pr_Prstock();
		
		$rPlist = $rProducts->listAllProducts();
		
		$arrRes = array();
		$arrResEmpty = array();		
		
		foreach($rPlist as $k => $v){
			
			$idProduct = $v["id_product"];
				
			$goSum = $rMove->getProductMoveSummaryByDateByCode(2, $idProduct, $dateBegin, $dateEnd,$idShop);
			$foSum = $rMove->getProductMoveSummaryByDateByCode(8, $idProduct, $dateBegin, $dateEnd,$idShop);
			$tiSum = $rMove->getProductMoveSummaryByDateByCode(3, $idProduct, $dateBegin, $dateEnd,$idShop); 
			$goAll = $rMove->getProductMoveSummaryByDateByCode(2, $idProduct, $dateBegin, $dateEnd); 
			
			$shopStock = $rStock->getShopStock($idProduct, $idShop);
			$whStock = $rStock->getWarehouseStock($idProduct);
			
			if($shopStock>0 && $foSum[0]['sum_qty'] == 0 && $goSum[0]['sum_qty'] == 0 ){
				$tmpArr = array();
				$tmpArr[] = $idProduct;
				$tmpArr[] = $v["code_product"];
				$tmpArr[] = $v["title_product"];
				$tmpArr[] = $shopStock;
				$tmpArr[] = $whStock;
				$tmpArr[] = $goAll[0]['sum_qty'];
				$tmpArr[] = $tiSum[0]['sum_qty'];
				if($v["code_product"]!="SERVICE" && $v["code_product"]!="CUSTPART" && $v["code_product"]!="ERROR1"  ){
				$arrRes[] = $tmpArr;
				}
			}
			
			if($shopStock <=0 && ($foSum[0]['sum_qty'] > 0 || $goSum[0]['sum_qty'] > 0) ){
				
				$tmpArr = array();
				$tmpArr[] = $idProduct;
				$tmpArr[] = $v["code_product"];
				$tmpArr[] = $v["title_product"];
				$tmpArr[] = $goSum[0]['sum_qty'];
				$tmpArr[] = $foSum[0]['sum_qty'];
				$tmpArr[] = $whStock;
				if($v["code_product"]!="SERVICE" && $v["code_product"]!="CUSTPART" && $v["code_product"]!="ERROR1"  ){
				$arrResEmpty[] = $tmpArr;				
				}	
			}
		}
		
		$this->view->arrRes = $arrRes;
		$this->view->arrResEmpty = $arrResEmpty;
		$this->view->idShop = $idShop;
	}
	
	/**
	 * parts sales summary is newly write function 
	 * it show the sale and faulty and give the weekly hold 
	 * it should combine with another 2 report above to give some recommendations
	 * @todo this function may have Bug need to improvment 
	 */
	public function partsSalesSummaryAction(){
		
		$dateBegin = $this->_getParam("date_begin");
		$dateEnd = $this->_getParam("date_end");
		
		
		if($dateBegin == ''){
			
			$dateEnd = Model_DatetimeHelper::getLastWeekSunday();
			$dateBegin = Model_DatetimeHelper::getLastWeekMonday();
			
		}
		
		
		$this->view->dateBegin = $dateBegin;
		$this->view->dateEnd = $dateEnd;
		
		$arrRCenter = array(1,2,3,4,5,6,7,8,9,10,12,13,14,15,16,17,18,19,21,23);
		
		
		$dateDiff = Model_DatetimeHelper::dateDiff($dateEnd, $dateBegin);
		$weeks = ($dateDiff + 1) / 7;
		
		
		
		$prProduct = new Model_DbTable_Pr_Prproducts();
		$prStockMove = new Model_DbTable_Pr_Prstockmovement();
		$prStock = new Model_DbTable_Pr_Prstock();
		$rOrder = new Model_DbTable_Pr_Order();
		
		
		
		$pList = $prStockMove->getStockMoveSumByDateByCode(2, $dateBegin, $dateEnd);
		$pListFo = $prStockMove->getStockMoveSumByDateByCode(8, $dateBegin, $dateEnd);
		$pListEi = $prStockMove->getStockMoveSumByDateByCode(7, $dateBegin, $dateEnd);
		
		$arrRes = array();
		$arrMax = array();
		
		$arrTmp = array();
		foreach($pList as $k => $v){
			
			$pRow = $prProduct->getProduct($v['id_product']);
			
			$arrTmp[] = trim($pRow['code_product']); // code
			$arrTmp[] = $pRow['title_product']; // title
			$arrTmp[] = $v['qtys']; // sales
			$arrTmp[] = $pRow['price_t']; // price 
			$arrTmp[] = 0; // faulty
			
		}
		
		// remove error correction 
		
		foreach($pListEi as $k => $v){
			
			$pRow = $prProduct->getProduct($v['id_product']);
			
			$key = array_search(trim($pRow['code_product']), $arrTmp, true);
			if($key === false){
				//error correction not in the list 
				$arrTmp[] = trim($pRow['code_product']); // code
				$arrTmp[] = $pRow['title_product']; // title
				$arrTmp[] = 0 - $v['qtys']; // sales
				$arrTmp[] = $pRow['price_t']; // price
				$arrTmp[] = 0; // faulty
			}
			else{
				
				$arrTmp[$key + 2] = $arrTmp[$key + 2]  -  $v['qtys'];
				
			}
		
		}
		
		// looking for faulty 
		
		foreach($pListFo as $k => $v){
			
			$pRow = $prProduct->getProduct($v['id_product']);
			$key = array_search(trim($pRow['code_product']), $arrTmp, true);
			
			if($key === false){
				
				$arrTmp[] = trim($pRow['code_product']); // code
				$arrTmp[] = $pRow['title_product']; // title
				$arrTmp[] = 0; // sales
				$arrTmp[] = $pRow['price_t']; // price
				$arrTmp[] = $v['qtys']; // faulty
				
			}
			else{
				
				$arrTmp[$key + 4] += $v['qtys']; 
			}
			
			
		}
		
		$arrRes = array_chunk($arrTmp,5);
		
		$arrFinal = array();
		
		
		foreach($arrRes as $k => $v){
			
			$arrFinalTmp = array();
			
			$idProduct = $prProduct->getProductID($v[0]);
			
			$cWhStock = $prStock->getWarehouseStock($idProduct);
			
			$cQtyOrder = $rOrder->qtyOnOrder($v[0]);
			
			$cSpStock = $prStock->getShopTotalStock($idProduct, $arrRCenter);
			
			$totalStock = $cSpStock + $cWhStock;
			
			$weekSales = $v[2] / $weeks;
			
			
			$whHold = ($weekSales == 0)?'-': round($cWhStock / $weekSales,1);
			$toHold = ($weekSales == 0)?'-': round($totalStock / $weekSales ,1);
			
			
			$arrFinalTmp = $v;
			
			$arrFinalTmp[] = $cWhStock;
			$arrFinalTmp[] = $whHold;
			$arrFinalTmp[] = $cSpStock;
			$arrFinalTmp[] = $totalStock;
			$arrFinalTmp[] = $toHold;
			$arrFinalTmp[] = $cQtyOrder;
			
			$arrMax[] = $v[2];
			
			$arrFinal[] = $arrFinalTmp;
			
		}
		
		array_multisort($arrMax,SORT_DESC,$arrFinal);
		
		//d($arrFinal);
		
		$this->view->arrRes = $arrFinal;
		
		//$this->view->pList = $pList;
		//var_dump($pList);
		
		if($_POST){
			
			$dateBegin = $_POST['date_begin'];
			$dateEnd = $_POST['date_end'];
			$url = '/repairparts/parts-sales-summary/date_begin/'.$dateBegin.'/date_end/'.$dateEnd;
			$this->_redirect($url);
		}
		
	}

	
	
	/**
	 * this is the function to refresh and create parts online order 
	 */
	public function lastWeekPartsSalesAction(){
		
		$shop = 1;
		$shop = $this->_getParam("shop");
		$staff = $this->_getParam("staff");
		$idShop = "";
		
		$thisMonday = Model_DatetimeHelper::getThisWeekMonday();
		$thisTuesday = Model_DatetimeHelper::adjustDays("add", $thisMonday, 1);
		
		
		
		$dateOrder = Model_DatetimeHelper::getThisWeekMonday("");
		$dateOrderTuesday = $dateOrder+1;//2014-08-05
		if($shop < 10 ){
			$idShop = "0".$shop;
		}else{
			
			$idShop = (string)$shop;
		}
		
		$partOrderNumber = "OD".$idShop.$dateOrder;
		$fakeOrderNumber = "OD".$idShop.$dateOrderTuesday;//2014-08-05
		
		$date2WeekBegin = Model_DatetimeHelper::adjustDays("sub",Model_DatetimeHelper::getLastWeekMonday(),7);
		$dateBegin = Model_DatetimeHelper::getLastWeekMonday();
		$dateEnd = Model_DatetimeHelper::getLastWeekSunday();
		
		
		$rProducts = new Model_DbTable_Pr_Prproducts();
		$rMove = new Model_DbTable_Pr_Prstockmovement();
		$rStock = new Model_DbTable_Pr_Prstock();
		$rBo = new Model_DbTable_Pr_Backorder();
		
		$rOrder = new Model_DbTable_Pr_Order();
		$rOrder->clearOrder($dateOrder, $shop);
		
		
		$arrPlist = array();
		
		$arrRes = array();
		
		$rListGo = $rMove->getStockMoveSumByDateByCode(2, $date2WeekBegin, $dateEnd,$shop);
		$rListFo = $rMove->getStockMoveSumByDateByCode(8, $dateBegin, $dateEnd,$shop);
		$rListEi = $rMove->getStockMoveSumByDateByCode(7, $dateBegin, $dateEnd,$shop);
		$rScreen = $rProducts->listAllLcd();

		if(!empty($rListGo)){
		foreach($rListGo as $k => $v){
			
			//$key = array_search($v['id_product'],$arrPlist);
			//if(!$key){
				
				
				$idProduct = $v['id_product']; //0
				$codeLine = $rProducts->getProduct($v['id_product']);
				$codeProduct = $codeLine['code_product']; //1
				$qtyLastWeek = round($v['qtys']/2,0);
				$qtyFo = 0;
				$qtyMax = $rMove->maxSold($idProduct, $dateEnd,4,$shop);
				$qtyOnhand = $rStock->getShopStock($idProduct, $shop);
				$qtyWh = $rStock->getWarehouseStock($idProduct);
				
				$arrTmp = array($idProduct,$codeProduct,$qtyLastWeek,$qtyFo,$qtyMax,$qtyOnhand,$qtyWh);
				if($codeProduct!="SERVICE"){
					$arrRes[] = $arrTmp;
				}
				$arrPlist[] = $idProduct;
				
			//}
			
		}
		}
		if(!empty($rListFo)){
		foreach($rListFo as $k1 => $v1){
			
			
			if(isset($v1['id_product'])){	
			$key = array_search($v1['id_product'],$arrPlist);
			if($key===false){
		
		
			$idProduct = $v1['id_product']; //0
			$codeLine = $rProducts->getProduct($v1['id_product']);
			$codeProduct = $codeLine['code_product']; //1
			$qtyLastWeek = 0;
			$qtyFo = $v1['qtys'];
			$qtyMax = $rMove->maxSold($idProduct, $dateEnd,4,$shop);
			$qtyOnhand = $rStock->getShopStock($idProduct, $shop);
			$qtyWh = $rStock->getWarehouseStock($idProduct);
		
			$arrTmp = array($idProduct,$codeProduct,$qtyLastWeek,$qtyFo,$qtyMax,$qtyOnhand,$qtyWh);
			$arrRes[] = $arrTmp;
			$arrPlist[] = $idProduct;
			}
			else{
			//update the Qty

				$arrRes[$key][3] += $v1['qtys'];
				
			}

			}
		}
		}
		
		if(!empty($rListEi)){
			foreach($rListEi as $k2 => $v2){
		
				$key = array_search($v2['id_product'],$arrPlist);
				if($key===false){
		
		
					$idProduct = $v2['id_product']; //0
					$codeLine = $rProducts->getProduct($v2['id_product']);
					$codeProduct = $codeLine['code_product']; //1
					$qtyLastWeek = 0;
					$qtyFo = 0 - $v2['qtys'];
					$qtyMax = $rMove->maxSold($idProduct, $dateEnd,4,$shop);
					$qtyOnhand = $rStock->getShopStock($idProduct, $shop);
					$qtyWh = $rStock->getWarehouseStock($idProduct);
		
					$arrTmp = array($idProduct,$codeProduct,$qtyLastWeek,$qtyFo,$qtyMax,$qtyOnhand,$qtyWh);
					$arrRes[] = $arrTmp;
					$arrPlist[] = $idProduct;
				}
				else{
					//update the Qty
		
					$arrRes[$key][3] -= $v2['qtys'];
		
				}
		
			}
		}

		

		if(!empty($rScreen)){
			foreach($rScreen as $k3 => $v3){
		
				$key = array_search($v3['id_product'],$arrPlist);
				if($key===false){
		
		
					$idProduct = $v3['id_product']; //0
					$codeProduct = $v3['code_product']; //1
					$qtyLastWeek = 0;
					$qtyFo = 0;
					$qtyMax = $rMove->maxSold($v3['id_product'], $dateEnd,4,$shop);
					$qtyOnhand = $rStock->getShopStock($v3['id_product'], $shop);
					$qtyWh = $rStock->getWarehouseStock($v3['id_product']);
		
					$arrTmp = array($idProduct,$codeProduct,$qtyLastWeek,$qtyFo,$qtyMax,$qtyOnhand,$qtyWh);
					$arrRes[] = $arrTmp;
					$arrPlist[] = $idProduct;
				}		
			}
		}
		
		
		
		$this->view->arrRes = $arrRes;
		
		$arrDup = array();
		
		
		foreach($arrRes as $row){
			
			$qtyOrder =$rOrder->orderQty($row[2], $row[4], $row[3], $row[5], $row[6]);
			
			$boQty = $rBo->getNotFullfilledBo($row[1], $shop);
			if(!empty($row[0]) && !in_array($row[0], $arrDup)){
				if($boQty){
					$finQty = $qtyOrder - $boQty;
					if($finQty < 0){
						$finQty = 0;
					}
				}else{
					$finQty = $qtyOrder;
				}
				
				
			$idOrder = $rOrder->addOrder($partOrderNumber, $shop, $thisMonday, $row[0], $row[1], $row[2], $row[3], $row[4], $row[5], $row[6],$finQty,0,0,$boQty,$staff);
			
			//2014-08-05 update all parts qty_onhand_cf 
			$product = $rProducts->getProduct($row[0]);
			
			if($product['is_lcd'] == null){
					$rOrder->updateStockTake($idOrder, (int)$row[5], $staff);
			}
			$arrDup[] = $row[0];

			}
		}
		
		//echo "<pre>";
		//var_dump($arrRes);
		//echo "</pre>";
		
		
		$this->_redirect("/repaircenter/online-order/shop/".$shop);
		
	}
	
	/**
	 * this funcion is for warehouse to pickup the online order 
	 */
	public function pickupSlipOrderAction(){
		
		$pon = $this->_getParam("pon");
		$rOrder = new Model_DbTable_Pr_Order();
		
		if($_POST){
			foreach($_POST['del'] as $order){
				$rOrder->deleteOrder($order);	
			}			
		}
		$this->view->pon = $pon;
		$this->view->oList = $rOrder->getByPONConfirmed($pon);
		
		$this->view->dateTime = Model_DatetimeHelper::dateToday()." ".Model_DatetimeHelper::timeNow();
			
	}
	/**
	 * this is the functon when warehouse parpare the order send notice to shop
	 * if the order can not been fullfilled , it falls into the back order 
	 * Modifyed on 2014-11-07 By Norman
	 * Add Back Order Function 
	 */
	public function orderDispatchAction(){
		

		$pon = $this->_getParam("pon");
		$idShop = (int)substr($pon,2,2);
		$dateOrder = substr($pon,4,4)."-".substr($pon,8,2)."-".substr($pon,10,2);
		$rOrder = new Model_DbTable_Pr_Order();
		$rProduct = new Model_DbTable_Pr_Prproducts();
		$rOrderAsKt = new Model_DbTable_Products_Stock_Transferadjuststatus();
		$rKaKtRecord = new Model_DbTable_Products_Stock_Kaktstatusrecord();
		$mail = new Model_Emailshandler();
		
		$this->view->pList = $pList = $rProduct->listAllProducts();
		$this->view->pon = $pon;
		$this->view->dateTime = Model_DatetimeHelper::dateToday()." ".Model_DatetimeHelper::timeNow();
		$arrAllo = array();
		if($_POST){
			$arrAllo = unserialize(base64_decode($_POST["arr_allocate_order"]));
			
			if(isset($_POST['btn_rd'])){
				$rOrder->removeDuplicated($pon);
			}
			
			if(isset($_POST["btn_add"])){
				
				/**
				 * remove duplicated
				 * @var unknown_type
				 */
				
				
				
				$idPro = $_POST["add_part_code"];
				$qty = $_POST["qty_add"];
				if($idPro!="" && is_numeric($qty) && $qty >0){
					if(isset($arrAllo[$idPro])){
						$arrAllo[$idPro] += $qty;
					}
					else{
						$arrAllo[$idPro] = $qty;
					}
				}
				
				
			}
			
			if(isset($_POST["btn_modify"]) || isset($_POST["btn_confirm"])){
				
				foreach($_POST["qty_alloc"] as $id => $qtyAllo){
					if($rOrder->isInOrder($pon,$id)){
						//update the qty 
						$rOrder->updateAllocateByPON($pon, $id, $qtyAllo);
					}
					else{
						//echo "New Insert";
						$pRow = $rProduct->getProduct($id);
						$rOrder->addOrder($pon, $idShop, $dateOrder, $id, $pRow['code_product'],0, 0, 0, 0, 0,0,$qtyAllo,null,$qtyAllo,null);
					}
					
					if(isset($_POST["id_modify"][$id])){
						
						$arrAllo[$id] = $qtyAllo;
					}
					//modify
					
				}
				
				if(isset($_POST["btn_confirm"])){
					echo "Order Confirmed, Email Sent,Order Listed In KAKT List, you may close the page now<br />";
					
					$subject = "Parts Order Ready For Dipatch,Please Confirm It";
					$mailBody = "copy the link below to your browser to confirm your order<br /> http://".SERVER_IP_PUBIC.":1080/repaircenter/order-confirm/pon/{$pon}";
					
					$rOrderAsKt->addStatus(trim($pon),"Repair Order",self::$rCenterMappRev[$idShop]);
					$idKa = $rOrderAsKt->getStatusByNumber(trim($pon));
					//var_dump($idKa);
					$rKaKtRecord->addRecord($idKa["id"],1,"Phone Repair");									
					$shopHead = self::$rCenterMappRev[$idShop];
					$sh = new Model_DbTable_Shoplocation();
					$shopMail = $sh->getShopMailByHead($shopHead);
					$mail->sendActionEmail($shopMail,$subject,$mailBody);
					
					/**
					 * Back Order function 
					 */
					
					$bOrder = new Model_DbTable_Pr_Backorder();
					$poList = $rOrder->getByPON($pon);
					
					foreach($poList as $row => $line){
							$totalQty = $line['qty_order_actual'] + $line['qty_backorder'];
							$boQty = $bOrder->getLastNotFullfilledBo($line['code_product'], $line['id_shop']);
							if($totalQty > 0 && $line['qty_allocate'] == 0){	
								if($boQty){
									$bOrder->updateBoQty($boQty['id_bo'], $totalQty);
								}else{						
									$bOrder->addBackorder($line['id_product'],$line['code_product'],$line['id_shop'],$totalQty,$totalQty,0,Model_DatetimeHelper::dateToday(),null,$line['part_order_number'],1);		
								}
							}else{
								
								if($boQty){
									$bOrder->fullfillBackOrder($boQty['id_bo'], Model_DatetimeHelper::dateToday());
								}
							}
							
					}
				}				
				
			}
		
		}
		$this->view->arrAllo = $arrAllo; 
		$this->view->strArrAllo = base64_encode(serialize($arrAllo));
		
		$this->view->oList = $rOrder->getByPON($pon);
		
		//var_dump($arrAllo);
		
	}
	/**
	 * This function was allocated to shop however 
	 * sometimes they click twice 
	 * so later it return to warehouse and only them can 
	 * Active the  order 
	 * Active order means show to the shop the order is actived and
	 * add stock on the actual shop stock 
	 */
	public function orderActivationAction(){
		
		$pon = $this->_getParam("pon");
		$this->view->orderNo = $pon;
			
		$rOrder = new Model_DbTable_Pr_Order();
		$rProduct = new Model_DbTable_Pr_Prproducts();
		$rMove = new Model_DbTable_Pr_Prstockmovement();
		$rStock = new Model_DbTable_Pr_Prstock();
		$rOrderAsKt = new Model_DbTable_Products_Stock_Transferadjuststatus();
		$kaktRecord = new Model_DbTable_Products_Stock_Kaktstatusrecord();
				
		$oList = $rOrder->getByPON($pon);
		$moveRow = $rMove->getPartsRecordByJobId($pon);
		
		if(!empty($moveRow)){
			$this->view->error = true;
		}
		
		if(isset($_POST['btn_confirm'])){
		
		foreach($oList as $key => $v){
	
		if(!empty($moveRow)){
			echo "Order Already Actived, Do not Need to do it again";
			break;
		}	
		if($v["qty_allocate"]>0){
		$rStock->descreaseStockWarehouse($v["id_product"], $v["qty_allocate"]);
		//shop stock +
		$rStock->increaseStockShop($v["id_product"], $v["qty_allocate"],$v["id_shop"]);
		//record movement
		$rMove->addMovement(3,$v["id_product"], $v["qty_allocate"],"repair Parts Order",$v['id_shop'],trim($pon));
		}	
		}
			
		$idKa = $rOrderAsKt->getStatusByNumber(trim($pon));
		$rOrderAsKt->activeTheTransfer($idKa["id"],Model_DatetimeHelper::dateToday(),'Phone Repair');
		$kaktRecord->addRecord($idKa["id"],99,"repair part");
		$rOrder->OrderSent(trim($pon));
			
		echo " You may Close the Window Now";
		//active kakt
		}
		
		$this->view->oList = $oList;
		
	}
	
	/**
	 * This is the version which techincian record the parts 
	 * it give the staff to verify if the parts is correct match the job and 
	 * if the screen is working 
	 */
	public function recordCustomerPartsAction(){
		
		$rjob = new Model_DbTable_Repairjob();
		$arrIdJob = array();
		
		if($_POST){
			
			$arrIdJob = unserialize(base64_decode($_POST["str_jobid"]));
			
			
			if(isset($_POST['btn_save'])){
				
				$this->view->showBarcode = true;
				
				$rjob->custPartRecord($_POST["last_id_job"],$_POST['is_correct'],$_POST['text_incorrect']);
			}
			else{
				
				$arrIdJob[] = $_POST["id_job"];
				//var_dump($arrIdJob);
				
				$this->view->showBarcode = false;
				$this->view->lastJobID = $_POST["id_job"];
			}
		
			
		}else{
			
			$this->view->showBarcode = true;
		}
		
		
		$this->view->strJobID = base64_encode(serialize($arrIdJob));
		$this->view->arrIdJob = $arrIdJob;
		
	}
	
	/**
	 * this if the version of record customer parts for non tech
	 * they don't check the parts quality , it just record the parts has been returned or not 
	 */
	
	public function recordCustomerPartsExpressAction(){
	
		$rjob = new Model_DbTable_Repairjob();
		$arrIdJob = array();
	
		if($_POST){
				
			$arrIdJob = unserialize(base64_decode($_POST["str_jobid"]));
				
			$rjob->custPartRecord($_POST["id_job"],1,"");
			$arrIdJob[] = $_POST["id_job"];
			$this->view->lastJobID = $_POST["id_job"];						
		}
	
		$this->view->strJobID = base64_encode(serialize($arrIdJob));
		$this->view->arrIdJob = $arrIdJob;
	
	}	
	
	/**
	 * this function is not in good use 
	 * the funcion export all the active price in excel format
	 */
	
	public function exportPartsPriceAction(){
		//export 
		$option = $this->_getParam("all");
		
		$rProduct = new Model_DbTable_Pr_Prproducts();
		$rList = $rProduct->listAllWithBonus();
		
		if($option == "yes"){
			
			$rList = $rProduct->listAllProducts();
		}
		
		if($option == "active"){
			
			$rList = $rProduct->listAllActive();
		}
		
		$dateToday = Model_DatetimeHelper::dateToday();
		$timeNow = Model_DatetimeHelper::timeNow("-");
		$fileName = "PRPRICE-".$dateToday."-".$timeNow;
		
		$arrPartPrice = array();
		
		foreach($rList as $key => $v){
			 $arrTmp = array();
			 $arrTmp[] = $v["id_product"];
			 $arrTmp[] = $v["code_product"];
			 $arrTmp[] = $v["title_product"];
			 $arrTmp[] = $v["price_a"];
			 $arrTmp[] = $v["price_b"];
			 $arrTmp[] = $v["price_c"];
			 $arrTmp[] = $v["price_d"];
			 $arrTmp[] = $v["price_e"];
			 $arrTmp[] = $v["price_f"];
			 $arrTmp[] = $v["price_g"];
			 $arrTmp[] = $v["price_h"];
			 $arrTmp[] = $v["price_i"];
			 $arrTmp[] = $v["price_j"];
			 $arrTmp[] = $v["price_k"];
			 $arrTmp[] = $v["price_l"];
			 $arrTmp[] = $v["price_m"];
			 $arrTmp[] = $v["price_n"];
			 $arrTmp[] = $v["price_o"];
			 $arrTmp[] = $v["price_p"];
			 $arrTmp[] = $v["price_q"];
			 $arrTmp[] = $v["price_r"];
			 $arrTmp[] = $v["price_s"];
			 $arrTmp[] = $v["price_t"];
			 $arrTmp[] = $v["act_cost"];
			 $arrTmp[] = $v["amt_full_bonus"];
			 $arrTmp[] = $v["amt_dis_bonus"];
			 $arrTmp[] = $v["active"];
			 $arrPartPrice[] = $arrTmp;
		}
		
		$fl = new Model_Fileshandler();
		$fl->exportPartsPriceExcel($fileName, $arrPartPrice);
		
		
	}
	
	/**
	 * This function not start YET
	 */
	public function shopBorrowSummaryAction(){
		
	}
	
	/**
	 * This page is for driver to gather  how many items should be return 
	 * driver will print out this page on day 1 / 2 
	 * it shows the RMA qty and customer parts Qty
	 */ 
	public function thisWeekReturnAction(){
		
		$this->view->dateBegin = $dateBegin = Model_DatetimeHelper::getLastWeekMonday();
		$this->view->dateEnd = $dateEnd = Model_DatetimeHelper::getLastWeekSunday();
		
		$isFirst = $this->_getParam("day");
		$arrShop = array();
		if($isFirst ==1 ){
			$arrShop = array("BBPC","EPIC","HPIC","NLPC","WBIC","WBPC","WGPC","WGIC");
		}
		else{
			$arrShop = array("BHPC","BSIC","BSPC","BSXP","FGIC","KCPC","PMIC","PMPC","SLIC","CBIC","CBPC");
		}	
		sort($arrShop,SORT_ASC);
		
		$fp = new Model_DbTable_Faultyproduct();
		$rMove = new Model_DbTable_Pr_Prstockmovement();
		$rPro = new Model_DbTable_Pr_Prproducts();
		$rJob = new Model_DbTable_Repairjob();
		
		
		
		$arrList = array();
		foreach($arrShop as $shop){
			//echo $shop;
			$fList = $fp->listAllUnhandledFaultyByShopByDate($shop, $dateBegin, $dateEnd);
			//var_dump($fList);
			$rList = $rMove->getStockMoveByDateByCode(2, $dateBegin,$dateEnd,self::$rCenterMapping[$shop]);
			$arrJobIdList = array();
			if(in_array($shop,self::$rCenterMappRev)){
			foreach($rList as $partrow){
				$rPDetailRow = $rPro->getProduct($partrow['id_product']);
				//var_dump($partrow);
				if($rPDetailRow['w_bonus']){
					
					$rProMove = $rMove->getProductMoveByDateByCode(2,$partrow['id_product'], $dateBegin,$dateEnd,self::$rCenterMapping[$shop]);
					//var_dump($rProMove);
					
					foreach($rProMove as $k => $v){
						
						if(is_numeric($v["id_job"])){
						$rJobRow = $rJob->getJob($v["id_job"]);
						//var_dump($rJobRow);
						if($rJobRow["cust_part"]==0){
							//echo $v["id_job"]."<br/>";
							$arrJobIdList[] = $v["id_job"];
						}
						}
						
					}
					
				}
			}
			}
			$arrJobIdList = array_unique($arrJobIdList);
			
			$tmpArr = array($shop,($fList)?Count($fList):0,Count($arrJobIdList));
			$arrList[] = $tmpArr;
		}
		
		//var_dump($arrList);
		$this->view->arrList = $arrList;
	}
	/*
	 * One part can have up to 26 price category 
	 * this page is use to manager this price category 
	 * show to staff or edit only 
	 * and what is the names
	 */
		public function managePriceCategoryAction(){
		
		$prCate = new Model_DbTable_Pr_Pricecategory();
		
		if($_POST){
			//var_dump($_POST);
			foreach($_POST['id_price_category'] as $k => $v){
				$active = (isset($_POST['active'][$k]))?1:0;
				$activeEdit = (isset($_POST['active_edit'][$k]))?1:0;
				$prCate->updatePricecategory($k,$_POST['title_category'][$k],$_POST['comment_category'][$k],$active,$activeEdit,$_POST['bk_color'][$k],$_POST['order'][$k]);
			}
		}
		
		$this->view->pList = $prCate->listAll();
		//var_dump($this->view->pList);
	
	}
	
	/**
	 * this is to re-print the borrow page 
	 */
	public function printBorrowPageAction(){
		
		$idJob = $this->_getParam("jid");
		if($idJob!=""){
		$prLoan = new Model_DbTable_Pr_Loan();
		$this->view->borrowCodes = $prLoan->getByJobId($idJob);
		//var_dump($this->view->borrowCodes);
		}
	}
	
	/**
	 * this page is for warehouse to create the Ad from parts stock take 
	 * this is the page for individual page 
	 */
	public function partsStockTakeSummaryShopAction(){
		
		$idShop = $this->_getParam("shop");
		$email = $this->_getParam("email");
		
		$sh = new Model_DbTable_Shoplocation();
		
		$shopHead = self::$rCenterMappRev[$idShop];
		$emailAddr = $sh->getStoreManMailByHead($shopHead);
		$this->view->emailAddr = $emailAddr;
		
		$dateOrder = Model_DatetimeHelper::getThisWeekMonday();
		$dateOrderTuesday = Model_DatetimeHelper::adjustDays('add', $dateOrder, 1);
		$dateReceive = $this->_getParam("date");
		
		if($dateReceive!=""){
				
			$dateOrder = $dateReceive;
			$dateOrderTuesday = Model_DatetimeHelper::adjustDays('add', $dateOrder, 1);
		}

		$prOrder = new Model_DbTable_Pr_Order();
		$stInfo = new Model_DbTable_Roster_Stafflogindetail();
		$pList = array();
		$pListTuesday = array();
		
		$stExist = $prOrder->stocktakeExist($dateOrder, $idShop);
		$stExistTuesday = $prOrder->stocktakeExist($dateOrderTuesday, $idShop);
		
		if(!$stExist){
			// not exist
			$pList['Message']="Stock Take Not Generated, Or , No Parts Consumption Last Week."; 
		}
		else{
			// exist 
			
			//finish?
			$ifFinish = $prOrder->stockTakeDone($idShop,$dateOrder);
			
			
			if($ifFinish[0]){
				$pList = $prOrder->listDiffByDateByShop($dateOrder, $idShop);
				if($pList == false){
					$stLine = $stInfo->getDetail($ifFinish[1]);
					$pList['Message'] = "Stock Take Finish WithOut Any Difference By {$stLine['ni']}";
				}
			}
			
			// not finish 
			
			else{
				$pList['Message'] = "Stock Take Still Pending for Finish";
			}
			
		}
		
	if(!$stExistTuesday){
			// not exist
			$pListTuesday['Message']="Tuesday Parts Stock Take Not Generated."; 
		}
		else{
			// exist 
			
			//finish?
			$ifFinish = $prOrder->stockTakeDone($idShop,$dateOrderTuesday);
			
			
			if($ifFinish[0]){
				$pListTuesday = $prOrder->listDiffByDateByShop($dateOrderTuesday, $idShop);
				if($pListTuesday == false){
					$stLine = $stInfo->getDetail($ifFinish[1]);
					$pListTuesday['Message'] = "Tuesday Parts Stock Take Finish WithOut Any Difference By {$stLine['ni']}";
				}
			}
			
			// not finish 
			
			else{
				$pListTuesday['Message'] = "Tuesday Parts Stock Take Still Pending for Finish";
			}
			
		}
		
		
		$this->view->prDiff2 = $pListTuesday;
		$this->view->prDiff = $pList;
		
		$this->view->email = $email;
	}
	
	/**
	 * This is the stock take reuslt page for warehouse 
	 * when it clicked it create the adjustment 
	 */
	public function partsStockTakeSummaryAction(){
		
		
		$dateOrder = Model_DatetimeHelper::getThisWeekMonday();
		$dateOrderTuesday = Model_DatetimeHelper::adjustDays('add', $dateOrder, 1);
		$dateReceive = $this->_getParam("date");
		
		
		$arrRepairShops = array(
				1 => 'Bayside Shops',
				2 => 'HOPE(CSIC)',
				3 => 'Brain',
				4 => 'BHPC',
				5 => 'HPIC',
				6 => 'CB GROUP',
				7 => 'WLIC',
				8 => 'EPIC',
				9 => 'WB Shops',
				10 => 'NLPC',
				11 => 'DCIC',
				12 => 'KCPC',
				13 => 'SLIC',
				14 => 'FGIC',
				15 => 'PMIC',
				16 => 'WG Shops',
				17 => 'ADPC',
				18 => 'BBPC',
				19 => 'CL Shops',
				20 => 'LU [Tech]',
				21 => 'BSIC',
				24 => 'JASON[Tech]'
		);
		
		if($dateReceive!=""){
			
			$dateOrder = $dateReceive;
			$dateOrderTuesday = Model_DatetimeHelper::adjustDays('add', $dateOrder, 1);
		}
		
		$prOrder = new Model_DbTable_Pr_Order();
		$rStock = new Model_DbTable_Pr_Prstock();
		$rMove = new Model_DbTable_Pr_Prstockmovement();
		
		
		$prDiffMonday = $prOrder->listAllDiffByDate($dateOrder);
		$prDiffTuesday = $prOrder->listAllDiffByDate($dateOrderTuesday);
		
		$prDiffSummary = array();
		$shopList = array();
			foreach($prDiffMonday as $k => $v){
				$tmpArr = array();
				$tmpArr = $v;
				$prDiffSummary[] = $tmpArr;
			
			}
			
			foreach($prDiffTuesday as $k2 => $v2){
				$tmpArr = array();
				$tmpArr = $v2;
				$prDiffSummary[] = $tmpArr;
				
			}
		
		//d($prDiffSummary);
		
		$this->view->date = $dateOrder;
		$this->view->shopList = $arrRepairShops;
		$this->view->prDiff = $prDiffSummary;

			
	}

	/**
	 * this is the actual stock adjustment page 
	 */
	public function stockTakeAdjustAction(){
		
		$rStock = new Model_DbTable_Pr_Prstock();
		$rMove = new Model_DbTable_Pr_Prstockmovement();
		$rPro = new Model_DbTable_Pr_Prproducts();
		$reMapping = unserialize(ARR_SHOP_GROUP_MAPPING_RCENTER);
		$shopBonus = new Model_DbTable_Products_Stock_Stocklost();
		
		$dateBegin = $_POST['date'];
		$dateEnd = Model_DatetimeHelper::adjustDays('add', $dateBegin, 6);
		
		$dateTody = Model_DatetimeHelper::dateToday("");
		$timeNow = Model_DatetimeHelper::timeNow("");
		
		$dateSunday = Model_DatetimeHelper::getThisWeekSunday("");
		
		if($_POST['shop_code'] < 10){
			$shopCode = "0".$_POST['shop_code'];
		}else{
			$shopCode = $_POST['shop_code'];
		}
		
		$adNo = "AD".$shopCode.$dateSunday;
		$rLost = 0;
	
		foreach($_POST['code_product'] as $key => $v){
			
			$diff = $_POST['qty_diff'][$key];
			$prLine = $rPro->getProductByCode($v);

			
			$rStock->increaseStockShop($prLine['id_product'],$diff,$_POST['shop_code']);
			
			if($diff >0){
				$rMove->addMovement(5, $prLine['id_product'], $diff,'Parts StockTake',$_POST['shop_code'],$adNo);
			}
			else{
				$rMove->addMovement(6, $prLine['id_product'], 0 - $diff,'Parts StockTake',$_POST['shop_code'],$adNo);
			}
			
			$tmpStock = $rStock->getShopStock($prLine['id_product'],$_POST['shop_code']);
			$rMove->addMovement(9, $prLine['id_product'], $tmpStock,'Parts ST Result',$_POST['shop_code'],$adNo);
			
			if(!empty($prLine['price_q'])){
				$rLost += round(($prLine['price_q']*$diff*0.9),2);	
					
			}else{
				$rLost += round(($prLine['price_a']/2*$diff*0.9),2);
			}
		}	
		
		 if($_POST['shop_code'] != 1 && $_POST['shop_code'] != 21){
		 	$shopKey = $_POST['shop_code'];
		 	$reMappingKey = $reMapping[$shopKey][0];
		 	$shopName = $reMapping[$shopKey][1];
		 	if($reMappingKey){
		 		$shopBonus->addStockLost($reMappingKey, $shopName, 7, $rLost, $dateBegin, $dateEnd);
		 	}
		 }else{
		 	$shopKey = $_POST['shop_code'];
		 	$reMappingKey = $reMapping[$shopKey][0];
		 	$shopName = $reMapping[$shopKey][1];
		 	$bonus = $shopBonus->getStockLostByShopIdTypePeriod($reMappingKey, 7, $dateBegin, $dateEnd);
		 	if(!$bonus){
		 		$shopBonus->addStockLost($reMappingKey, $shopName, 7, $rLost, $dateBegin, $dateEnd);
		 	}else{
		 		$lostTotal = $rLost + $bonus['stock_lost'];
		 		$shopBonus->updateStockLost($bonus['id'], $reMappingKey, $shopName, 7, $lostTotal, $dateBegin, $dateEnd);
		 	}
		 }
		
		echo "<h1>{$adNo}</h1>";
		
	}
	
	

	
	public function zNOUSEcsicAction(){
		/*
		$dateTody = Model_DatetimeHelper::dateToday("");
		$timeNow = Model_DatetimeHelper::timeNow("");
		$adNo = "AD".$dateTody.$timeNow;
		
		
		$rPro = new Model_DbTable_Pr_Prproducts();
		$rStock = new Model_DbTable_Pr_Prstock();
		$rMove = new Model_DbTable_Pr_Prstockmovement();

		$fl = fopen("csic.csv","r");
		
		while(($lineData = fgetcsv($fl,1000))!=false){
			
			$idPro = $rPro->getProductID(trim($lineData[0]));
			
			$rStock->increaseStockShop($idPro,0 - (int)trim($lineData[1]),2);
			$rStock->increaseStockWarehouse($idPro,trim($lineData[1]));
			
			$rMove->addMovement(4, $idPro, (int)trim($lineData[1]), "Norman-CSIC RETURN",2,$adNo);
			$rMove->addMovement(5, $idPro, (int)trim($lineData[1]), "Norman-CSIC RETURN",0,$adNo);
				
		}
		
		fclose($fl);
		
		//to 
		//ad
		//adjust stock 
		 
		*/
	}
	
	/**
	 * snap shot function is to record at a moment what is the stock QTY 
	 * it add a record in part move history doing 0 Qty adjustment 
	 * so the AR (Adjustment Result ) is current stock 
	 * snap shot act for all parts in the parts db
	 */
	public function snapshotAction(){
		
		$shop = $this->_getParam("shop");
		$staffName = $this->_getParam("staff");
		$reason = $this->_getParam("reason");
		
		$prPro = new Model_DbTable_Pr_Prproducts();
		$prStk = new Model_DbTable_Pr_Prstock();
		$prMove = new Model_DbTable_Pr_Prstockmovement();
		
		$pList = $prPro->listAllProducts();
		foreach($pList as $k => $v){
			$prMove->addMovement(9, $v['id_product'],0,"System Snapshot By ".$staffName,$shop,"For :".$reason);
			
		}
		echo "Done";
	}
	/**
	 * This function is made by leo 
	 * @author Leo	
	 * @version 2014-06-25
	 * For showing all the repair parts by shop
	 */
	public function repairPartsListAction(){
		$rProducts = new Model_DbTable_Pr_Prproducts();
		$rMove = new Model_DbTable_Pr_Prstockmovement();
		$dateBegin = $this->_getParam("date_begin");
		$dateEnd = $this->_getParam("date_end");
		$shop = unserialize(ARR_RCENTER_REV_MAPPING);
		//2014-07-01
		$myresult = array("ADPC"=>0,
		"BBPC"=>0,
		"BHPC"=>0,
		"BSIC"=>0,
		"BSPC"=>0,
		"BSXP"=>0,
		"CBPC"=>0,
		"CBIC"=>0,
		"CLIC"=>0,
		"CLPC"=>0,
		"CSIC"=>0,
		"DCIC"=>0,
		"EPIC"=>0,
		"EPPC"=>0,
		"FGIC"=>0,
		"HPIC"=>0,
		"KCPC"=>0,
		"NLPC"=>0,
		"PMIC"=>0,
		"PMPC"=>0,
		"SLIC"=>0,
		"WBIC"=>0,
		"WBPC"=>0,
		"WGIC"=>0,
		"WGPC"=>0,
		"WLIC"=>0);

		$barCode = 'PARTSSALES';
		foreach ($myresult as $key => $v){
		$myQty = 0;
		$invoProducts = Model_Aposinitnew::initAposInvPro($key);
		$myQty = $invoProducts->getProductSalesQtyByDates($dateBegin, $dateEnd, $barCode);
		$myresult[$key] = $myQty;
		}
	
		
		
		$repairpartsDetail = array();
		$list = array();
		$total = 0;
		
		
		$invHead = substr(Model_DatetimeHelper::dateToday(),2,2);
		$invHead = "L".$invHead;
		$repairpartsList = $rMove->listByJobCodeId(2, $invHead , $dateBegin, $dateEnd);
		foreach($repairpartsList as $key => $v){
				$tmpArr = array();
				$tmpArr = $v;
				//$idPro = $v['id_product'];
				$shopId = $v['shop_code'];
				$shopName = $shop[$shopId];
				$linePro = 	$rProducts->getProduct($v['id_product']);
				$tmpArr['code_product']= $linePro['code_product'];
				$tmpArr['title_product']= $linePro['title_product'];
				$tmpArr['shop_name'] = $shopName;
				$list[] = $tmpArr;
			//		$repairpartsDetail[] = $rProducts->getProduct($v['id_product']);
	
		}
		$this->view->list = $list;
		
		if(isset($_GET['submit'])&&($_GET['select']!=22)){
			$list2 = array();
			foreach($repairpartsList as $key => $v){
				if($_GET['select']==$v['shop_code']){
				
				$tmpArr = array();
				$tmpArr = $v;
				$shopId = $v['shop_code'];
				$shopName = $shop[$shopId];
				$linePro = 	$rProducts->getProduct($v['id_product']);
				$tmpArr['code_product']= $linePro['code_product'];
				$tmpArr['title_product']= $linePro['title_product'];
				$tmpArr['shop_name'] = $shopName;
				$total += $v['qty_product'];
				$tmpArr['total'] = $total;
				$list2[] = $tmpArr;
				
				}
			}
			$this->view->list = $list2;
		}else{
			$list2 = array();
			foreach($repairpartsList as $key => $v){
					
					$tmpArr = array();
					$tmpArr = $v;
					$shopId = $v['shop_code'];
					$shopName = $shop[$shopId];
					$linePro = 	$rProducts->getProduct($v['id_product']);
					$tmpArr['code_product']= $linePro['code_product'];
					$tmpArr['title_product']= $linePro['title_product'];
					$tmpArr['shop_name'] = $shopName;
					$list2[] = $tmpArr;
			
				}
			$this->view->list = $list2;
		}
	}

	/**
	 * @author Leo
	 * @version 2014-06-27
	 * For showing all the repair parts and service number by shop
	 */
	public function listPartSummaryAction(){
		$dateBegin = $this->_getParam("date_begin");
		$dateEnd = $this->_getParam("date_end");
		//var_dump($dateBegin);
		$arrRes = array();
		$arrStaff = array();
		$arrShop = array();
		$arrDate = array();
		$repairpartsDetail = array();
		$invPro = "";
		$list = array();
		//2014-07-01
	$myresult = array("ADPC"=>0,
		"BBPC"=>0,
		"BHPC"=>0,
		"BSIC"=>0,
		"BSPC"=>0,
		"BSXP"=>0,
		"CBPC"=>0,
		"CBIC"=>0,
		"CLIC"=>0,
		"CLPC"=>0,
		"CSIC"=>0,
		"DCIC"=>0,
		"EPIC"=>0,
		"EPPC"=>0,
		"FGIC"=>0,
		"HPIC"=>0,
		"KCPC"=>0,
		"NLPC"=>0,
		"PMIC"=>0,
		"PMPC"=>0,
		"SLIC"=>0,
		"WBIC"=>0,
		"WBPC"=>0,
		"WGIC"=>0,
		"WGPC"=>0,
		"WLIC"=>0);

		$barCode = 'PARTSSALES';
		foreach ($myresult as $key => $v){
		$myQty = 0;
		$invoProducts = Model_Aposinitnew::initAposInvPro($key);
		$myQty = $invoProducts->getProductSalesQtyByDates($dateBegin, $dateEnd, $barCode);
		$myresult[$key] = $myQty;
		}
		
		
		
		$rJobs = new Model_DbTable_Repairjob(Zend_Registry::get('db_remoteapp'));
		$shop = unserialize(ARR_RCENTER_REV_MAPPING);
		$rMove = new Model_DbTable_Pr_Prstockmovement(Zend_Registry::get('db_remoteapp'));
		$rPart = new Model_DbTable_Pr_Prproducts(Zend_Registry::get('db_remoteapp'));
		$rProducts = new Model_DbTable_Pr_Prproducts(Zend_Registry::get('db_remoteapp'));
		
		$rStatus = new Model_DbTable_Repairstatusrecord(Zend_Registry::get('db_remoteapp'));
		
		$jList = $rJobs->listAllFinishedJobsByDate($dateBegin, $dateEnd);
		
		$invHead = substr(Model_DatetimeHelper::dateToday(),2,2);
		$invHead = "L".$invHead;
		

		$repairpartsDetail = $rMove->listByJobCodeId(2,$invHead,$dateBegin,$dateEnd);

		foreach($repairpartsDetail as $key => $v){
				$tmpArr = array();
				$tmpArr = $v;
				//$idPro = $v['id_product'];
				$shopId = $v['shop_code'];
				$shopName = $shop[$shopId];
				$linePro = 	$rProducts->getProduct($v['id_product']);
				$tmpArr['code_product']= $linePro['code_product'];
				$tmpArr['title_product']= $linePro['title_product'];
				$tmpArr['shop_name'] = $shopName;
				$list[] = $tmpArr;
			//		$repairpartsDetail[] = $rProducts->getProduct($v['id_product']);
	
		}
		
		
		//echo "<pre>";
		foreach($jList as $job){
			$stJob = $rStatus->getLastStatus($job["id_job"]);
				
			if($stJob[0]["id_status"] == 90 ){
				$invPro = "";
				$shop =  strtoupper(trim($job["shop_code"]));
				if($shop == 'WHAL'){
					$invPro = Model_Aposinitnew::initAposInvPro('FGIC');
				}else{
					$invPro = Model_Aposinitnew::initAposInvPro($shop);
				}
				
				$invLine = "";
				$invLine2 = "";
				$inv1Count = "";
				$inv2Count = "";
		
				$inv1Disc = 0;
				$inv2Disc = 0;
		
		
				$inv1 = substr($job["invoice_no"],-8);
				$inv2 = "";
				$invLine = $invPro->getRepairInvoice("L1".$inv1);
		
				$inv1Count = count($invPro->getInvoiceProducts("L1".$inv1));
		
				$inv1Disc = $invPro->getInvoiceDiscount("L1".$inv1);
		
				if(strlen($job["invoice_no2"]) > 0){
		
					$inv2 = substr($job["invoice_no2"],-8);
					$invLine2 = $invPro->getRepairInvoice("L1".$inv2);
					$inv2Count = count($invPro->getInvoiceProducts("L1".$inv2));
					$inv2Disc = $invPro->getInvoiceDiscount("L1".$inv2);
				}
		
				//get repair parts
		
				$partsRes = $rMove->getPartsSummaryByJobId($job['id_job'],"price_b");

				//d($partsRes);
				//var_dump($tmprows);
				// bonus summary
				$wBonus = false;
				$maxBonusFull = 0;
				$maxBonusHalf = 0;
		
				$amtBonusPartsAmt = 1;
				$amtBonusParts = 0;
				$amtBonusService = 0;//2014-07-11
				$perfectBonus = 0;
				
				
				foreach($partsRes[0] as $part){
					$amtBonusParts += $amtBonusPartsAmt * $part[1];
					$amtBonusService += $amtBonusPartsAmt * $part[1];
					$perfectBonus += $amtBonusPartsAmt * $part[1];//2014-07-11
					$id = $rPart->getProductID($part[0]);
					$row = $rPart->getProduct($id);
					if($row['w_bonus']){
						$wBonus = true;
						if($row["amt_full_bonus"] > $maxBonusFull){
							$maxBonusFull = $row["amt_full_bonus"]; 
							$maxBonusHalf = $row["amt_dis_bonus"];
						}
					}
				}
				
				$amtBonus = "N/A";

				
				$repairDis = 0;
				$salesDis = 0;
				
				if($wBonus){
					
					if($job["invoice_no2"] == "" ){
						
						if($inv1Count==1){
							$repairDis = $partsRes[1] - $invLine;
						}
						if($inv1Count>1){
							$repairDis = $partsRes[1] - $invLine;
							$salesDis = $inv1Disc;
						}	
					}
					
					else{
						
						if($inv1==$inv2){
							
							if($inv1Count==1){
								$repairDis = $partsRes[1] - $invLine;
							}
							if($inv1Count>1){
								$repairDis = $partsRes[1] - $invLine;
								$salesDis = $inv1Disc;
							}
						}						
							else{

							$repairDis = $partsRes[1] - $invLine - $invLine2;
							$salesDis = $inv1Disc + $inv2Disc;
						}	
							
						}					
					
				}else{
					$amtBonusParts = 0;
					$amtBonusService = 0;
				}
				
				$bonusAmt = 0;
				
				if( ($repairDis + $salesDis) >0){
					
					$amtBonusParts = 0;
				}
				
				
				if($wBonus){
				if( ($repairDis < 5 && $salesDis < 5) || ($repairDis + $salesDis) < 5  ){
					
					$bonusAmt = $maxBonusFull;
					$maxBonusHalf = 0;
					
				}
				
				if(($repairDis >= 5 && $repairDis < 10 && $salesDis >= 5 && $salesDis < 10 ) || (($repairDis + $salesDis) >= 5 && ($repairDis + $salesDis) < 10)  ){
					$bonusAmt = $maxBonusHalf;
					$maxBonusFull = 0;
				}
				if(($repairDis + $salesDis) > 10){
					
					$bonusAmt = 0;
					
					$maxBonusHalf = 0;
					$maxBonusFull = 0;
					
					
				}
				
				$policyArray = $rJobs->bonusRule($job["id_job"]);

				if(!$policyArray[0] || !$policyArray[1] ||$job['fix_by_hq']==1){
					$bonusAmt = 0;
					$amtBonusParts = 0;
					$amtBonusService = 0;
				}
				
				}
				//WHo , what ,finish time , quote , invoices , who record 
				$tmpArr = array();
				
				$tmpArr["id_job"] = $job["id_job"];
				$tmpArr["date_start"] =  $job["date_start"];
				$tmpArr["repair_staff"] = $job["repair_staff"];
				
				$arrStaff[] =  $job["repair_staff"];
				
				$tmpArr["shop_code"] = $job["shop_code"];
				
				$arrShop[] = $job["shop_code"]; 
				
				$tmpArr["mobile_model"] = $job["mobile_model"];
				$tmpArr["quot_price"] = $job["quot_price"];
				$tmpArr["invoice_no"] = $job["invoice_no"];
				$tmpArr["invoice_qty"] =  $inv1Count;
				$tmpArr["invoice_amt"] = $invLine;
				$tmpArr["invoice_no2"] = $job["invoice_no2"];
				$tmpArr["invoice_qty2"] = $inv2Count;
				$tmpArr["invoice_dis"] = $inv1Disc;
				$tmpArr["invoice_dis2"] = $inv2Disc;
				$tmpArr["invoice_amt2"] = $invLine2;
				$tmpArr["staff_record"] = $job["staff_record"];
				$tmpArr["time_record"] = $job["time_record"];
				$tmpArr["part_sum"] = $partsRes;
				$tmpArr["w_bonus"] = $wBonus;
				$tmpArr["repair_disc"] = $repairDis;
				$tmpArr["sales_disc"] = $salesDis;
				$tmpArr["bonus_amt"] = $bonusAmt;
				$tmpArr["full_bonus_amt"] = $maxBonusFull;
				$tmpArr["dis_bonus_amt"] = $maxBonusHalf;
				
				
				$arrDate[] = $job["time_record"];
				
				$tmpArr['bonus_rule'] = $rJobs->bonusRule($job["id_job"]);
				$tmpArr['bonus_part'] = $amtBonusParts;
				$tmpArr['bonus_service'] = $amtBonusService;
				$tmpArr['perfect_bonus'] = $perfectBonus;
				 
				$arrRes[] = $tmpArr;
			}	
		}
		
		//array_multisort($arrStaff,SORT_ASC,$arrShop,SORT_ASC,$arrDate,SORT_ASC,$arrRes);
			array_multisort($arrShop,SORT_ASC,$arrStaff,SORT_ASC,$arrDate,SORT_ASC,$arrRes);
		//d($arrRes);
		//echo "</pre>";
		
		$this->view->comparePrice = $list;
		$this->view->arrRes = $arrRes;
		$this->view->repairPartDetail = $myresult;


	}
	
	public function alexTiAction(){
		
		$fc = fopen('parts_cost.csv','r');
		$arrCost = array();
		
		while(($lCost = fgetcsv($fc,100))!=false){
			$arrCost[$lCost[0]] = $lCost[1];
		}
		
		fclose($fc);
		
		
		$rMove = new Model_DbTable_Pr_Prstockmovement();
		
		$rSiList = $rMove->formatMoveByShopByCode($rMove->getMoveByShopByCode(31,23));
		$rTiList = $rMove->formatMoveByShopByCode($rMove->getMoveByShopByCode(3, 23));
		$rAoList = $rMove->formatMoveByShopByCode($rMove->getMoveByShopByCode(6,23));
		$rFoList = $rMove->formatMoveByShopByCode($rMove->getMoveByShopByCode(8,23));
		
		$rProducts = new Model_DbTable_Pr_Prproducts();
		
		$arrSi = array();
		foreach($rSiList as $key => $v){
			$rLine = $rProducts->getProduct($key);
			$code = $rLine['code_product'];
			$des = $rLine['title_product'];
			$qty = $v;
			$unitCost = (isset($arrCost[$code]))?$arrCost[$code]:0;
			$subTotal = $qty * $unitCost;
			$arrSi[] = array($code,$des,$qty,$unitCost,$subTotal);
		}
		$arrTi = array();
		foreach($rTiList as $key => $v){
			$rLine = $rProducts->getProduct($key);
			$code = $rLine['code_product'];
			$des = $rLine['title_product'];
			$qty = $v;
			$unitCost = (isset($arrCost[$code]))?$arrCost[$code]:0;
			$subTotal = $qty * $unitCost;
			$arrTi[] = array($code,$des,$qty,$unitCost,$subTotal);
		}
		$arrAo = array();
		
		foreach($rAoList as $key => $v){
			$rLine = $rProducts->getProduct($key);
			$code = $rLine['code_product'];
			$des = $rLine['title_product'];
			$qty = $v;
			$unitCost = (isset($arrCost[$code]))?$arrCost[$code]:0;
			$subTotal = $qty * $unitCost;
			$arrAo[] = array($code,$des,$qty,$unitCost,$subTotal);
		}
		$arrFo = array();
		foreach($rFoList as $key => $v){
			$rLine = $rProducts->getProduct($key);
			$code = $rLine['code_product'];
			$des = $rLine['title_product'];
			$qty = $v;
			$unitCost = (isset($arrCost[$code]))?$arrCost[$code]:0;
			$subTotal = $qty * $unitCost;
			$arrFo[] = array($code,$des,$qty,$unitCost,$subTotal);
		}
		
		$this->view->arrSi = $arrSi;
		$this->view->arrTi = $arrTi;
		$this->view->arrAo = $arrAo;
		$this->view->arrFo = $arrFo;
		
	}
	
	public function alexRepairJobsAction(){
		
		
		$rjob = new Model_DbTable_Repairjob(Zend_Registry::get('db_remoteapp'));
		$rStock = new Model_DbTable_Pr_Prstockmovement(Zend_Registry::get('db_remoteapp'));
		$rStockAd = new Model_DbTable_Pr_Stockmove_Ad(Zend_Registry::get('db_remoteapp'));
		$rProducts = new Model_DbTable_Pr_Prproducts(Zend_Registry::get('db_remoteapp'));
		$rBorrow = new Model_DbTable_Pr_Loan(Zend_Registry::get('db_remoteapp'));
		$invPro = Model_Aposinitnew::initAposInvPro('FGIC');
		$file = new Model_Fileshandler();

		
		if(isset($_POST['submit'])){
			$dateBegin = $_POST['date_begin'];
			$dateEnd = $_POST['date_end'];
			
			$alexJob = $rjob->getAllfinishAlexJobByDate($dateBegin, $dateEnd);
			
			$alexOrder = $rStock->getAlexOrder(31, $dateBegin, $dateEnd,23);
			$alexIn = $rBorrow->AlexIn($dateBegin,$dateEnd);
			$arrAlexOut = $rBorrow->AlexOut($dateBegin, $dateEnd);
			$alexOut = array();
			foreach ($arrAlexOut as $k => $v){
			
				$rDetail = $rjob->getJob($v['id_job']);
				if($rDetail){
					if($rDetail['repair_staff'] != 380){
							
						$alexOut[] = $v;
					}
				}
			}
			$this->view->alexOut = $alexOut;
			$this->view->alexIn = $alexIn;
			$this->view->orderList = $alexOrder;

			$arrRes = array();
			$arrProblem = array();
			foreach ($alexJob as $k => $job){
				$idJob = $job['id_job'];
				if(is_numeric($idJob)){
					$brand_a = $job['mobile_model'];
					$cost_a = 1;
					$brand_s = $job['mobile_model'];
					$rType_a = $job['repair_type'];
					$rrp_a = $job['quot_price'];
					$invoice_id = array($job['invoice_no'],$job['invoice_no2']);
					$totalCharge = 0;
					if($job['invoice_no']!=''){
						$invProList = $invPro->getInvoiceProducts($job['invoice_no']);
						//d($invProList);
						foreach($invProList as $invItem){
							if(trim($invItem['SCODE'])=='PHONEREPAIR')
								$totalCharge += $invItem['AMOUNT'];
						}
					}
					
					$arrParts = array();
					$totalCost = 0;
					$totalqty = 0;
					$tmprows = $rStock->getPartsRecordByJobId($idJob);
						
					if(isset($tmprows) && count($tmprows) > 0){
					
						foreach($tmprows as $key => $value){
					
							$rowProduct = $rProducts->getProduct($value['id_product']);
							$bLine = $rBorrow->getByStMoveCode($value['id_move']);
							$borrow = ($bLine)?$bLine['b_code']:'-';
							$bConfirm = ($bLine)?$bLine['confirmed']:'-';
							if($value['code_move'] == 2 || $value['code_move'] == 7){
					
								$qty = ($value['code_move'] == 2)?$value['qty_product']:( 0 - $value['qty_product']);
								$costParts = 10000;
								if(isset($rowProduct['price_t'])){
							 		$costParts = round($rowProduct['price_t']*1.1,2);
							 	}
								$totalCost += $qty * $costParts;
								$totalqty += $qty;
									
								$arrParts[] = array(
										$rowProduct['code_product'],
										$rowProduct['title_product'],
										$costParts,
										$qty,
										$borrow,
										$bConfirm
								);
							}
					
						}
					}
					
					
					if( $rrp_a == $totalCharge && $totalCost < 10000 && $costParts < 10000){
					
						$arrRes[] = array(
								$idJob,
								$brand_a,
								$brand_s,
								$rType_a,
								$cost_a,
								$rrp_a,
								$invoice_id,
								$arrParts,
								$totalCharge,
								$totalCost,
								$job['repair_staff'],
								$totalqty

						);
					}
					else{

						
						$arrProblem2[] = array(
								$idJob,
								$brand_a,
								$brand_s,
								$rType_a,
								$cost_a,
								$rrp_a,
								$invoice_id,
								$arrParts,
								$totalCharge,
								$totalCost,
								$job['repair_staff'],
								$totalqty
									
						);
							
					}
					
					
					
				}
				
			}	
			
			foreach($arrProblem2 as $k => $v){
				$arrInv[] = $v[6][0];
			}
			$array = array_unique($arrInv);
			$sameInvoice = array();
			$checkList = array();
			foreach($array as $k2 => $v2){
				$checkTotal = 0;
				$checkAposTotal = 0;
				$sameJob = $rjob->getSameInvoiceJobByAlexByDate($v2, $dateBegin, $dateEnd);
				if(count($sameJob)>=2){
					foreach($sameJob as $k3 => $v3){
						$checkTotal += $v3['quot_price'];
					}
					if($v2!=''){
						$invProList = $invPro->getInvoiceProducts($v2);
						//d($invProList);
						foreach($invProList as $invItem){
							if(trim($invItem['SCODE'])=='PHONEREPAIR')
								$checkAposTotal += $invItem['AMOUNT'];
						}
					}
					if($checkAposTotal == $checkTotal){
						foreach($sameJob as $k4 => $v4){
							 array_push($sameInvoice, $v4['id_job']);
							 $idJob = $v4['id_job'];
							 $brand_a = $v4['mobile_model'];
							 $cost_a = 1;
							 $brand_s = $v4['mobile_model'];
							 $rType_a = $v4['repair_type'];
							 $rrp_a = $v4['quot_price'];
							 $invoice_id = array($v4['invoice_no'],$v4['invoice_no2']);
							 $totalCharge = 0;
							 	$invProList = $invPro->getInvoiceProducts($v2);
							 	//d($invProList);
							 	foreach($invProList as $invItem){
							 		if(trim($invItem['SCODE'])=='PHONEREPAIR'){
							 			$totalCharge += $invItem['AMOUNT'];
							 		}
							 	}
				
							 		
							 	$arrParts = array();
							 	$totalCost = 0;
							 	$totalqty = 0;
							 	$tmprows = $rStock->getPartsRecordByJobId($idJob);
							 
							 	if(isset($tmprows) && count($tmprows) > 0){
							 			
							 		foreach($tmprows as $key => $value){
							 				
							 			$rowProduct = $rProducts->getProduct($value['id_product']);
							 			$bLine = $rBorrow->getByStMoveCode($value['id_move']);
							 			$borrow = ($bLine)?$bLine['b_code']:'-';
							 			$bConfirm = ($bLine)?$bLine['confirmed']:'-';
							 			if($value['code_move'] == 2 || $value['code_move'] == 7){
							 					
							 				$qty = ($value['code_move'] == 2)?$value['qty_product']:( 0 - $value['qty_product']);
							 				$costParts = 10000;
							 				if(isset($rowProduct['price_t'])){
							 					$costParts = round($rowProduct['price_t']*1.1,2);
							 				}
							 				$totalCost += $qty * $costParts;
							 				$totalqty += $qty;
							 					
							 				$arrParts[] = array(
							 						$rowProduct['code_product'],
							 						$rowProduct['title_product'],
							 						$costParts,
							 						$qty,
							 						$borrow,
							 						$bConfirm
							 				);
							 			}
							 				
							 		}
							 	}
							 		

							$tmpArr = array(
							 				$idJob,
							 				$brand_a,
							 				$brand_s,
							 				$rType_a,
							 				$cost_a,
							 				$rrp_a,
							 				$invoice_id,
							 				$arrParts,
							 				$totalCharge,
							 				$totalCost,
							 				$v4['repair_staff'],
							 				$totalqty);

							$checkList[$v2][] = $tmpArr;
						}
						
					}
				}
				
			}
			foreach($arrProblem2 as $k5 => $v5){
				if(!in_array($v5[0], $sameInvoice)){
					$arrProblem[] = $v5;
				}
			}
	
			$this->view->dateBegin = $dateBegin;
			$this->view->dateEnd = $dateEnd;
			$this->view->checkList = $checkList;
			$this->view->arrRes = $arrRes;
			$this->view->arrProblems = $arrProblem;
		}
		
		if(isset($_POST['export'])){
			
			$jobId = $_POST['id_job'];
			$repair = $_POST['repair_by'];
			$model = $_POST['model'];
			$repiarType = $_POST['repair_type'];
			$charge = $_POST['charge'];
			$inv1 = $_POST['inv1'];
			$inv2 = $_POST['inv2'];
			$chargeSys = $_POST['charge_sys'];
			$parts = $_POST['parts'];
			$partsQty = $_POST['parts_qty'];
			$cost = $_POST['cost'];
			$tmp1 = $_POST['sep_parts'];
			$sepParts = array();
			foreach($tmp1 as $k6 => $v6){
					$sepParts[$k6] = implode("+",$v6); 
			}
			$checkJobId = "";
			$pbJobId = "";
			if(!empty($_POST['check_id_job'])){
				$checkJobId = $_POST['check_id_job'];
				$checkrepair = $_POST['check_repair_by'];
				$checkmodel = $_POST['check_model'];
				$checkrepiarType = $_POST['check_repair_type'];
				$checkcharge = $_POST['check_charge'];
				$checkinv1 = $_POST['check_inv1'];
				$checkchargeSys = $_POST['check_charge_sys'];
				$checkparts = $_POST['check_parts'];
				$checkpartsQty = $_POST['check_parts_qty'];
				$checkcost = $_POST['check_cost'];
			
				$tmp2 = $_POST['check_sep_parts'];
				$checkSepParts = array();
				foreach($tmp2 as $k6 => $v6){
					$checkSepParts[$k6] = implode("+",$v6);
				}
			}
			
			if(!empty($_POST['pb_id_job'])){
				$pbJobId = $_POST['pb_id_job'];
				$pbrepair = $_POST['pb_repair_by'];
				$pbmodel = $_POST['pb_model'];
				$pbrepiarType = $_POST['pb_repair_type'];
				$pbcharge = $_POST['pb_charge'];
				$pbinv1 = $_POST['pb_inv1'];
				$pbinv2 = $_POST['pb_inv2'];
				$pbchargeSys = $_POST['pb_charge_sys'];
				$pbparts = $_POST['pb_parts'];
				$pbpartsQty = $_POST['pb_parts_qty'];
				$pbcost = $_POST['pb_cost'];
				$tmp3 = $_POST['pb_sep_parts'];
				$pbSepParts = array();
				foreach($tmp3 as $k6 => $v6){
					$pbSepParts[$k6] = implode("+",$v6);
				}
			}
	
			
			$arrNJob = array();
			$arrCJob = array();
			$arrPJob = array();
			
			if($jobId){
				foreach ($jobId as $k => $v){
					$count = count($parts[$k]);
					$i = 0;
					$arrTmp2 = "";
					foreach($parts[$k] as $k2 => $v2){
						$i++;
						if($i != $count){
							$arrTmp2 .= $k2."*".$v2."   ";
						}else{
							$arrTmp2 .= $k2."*".$v2."   ";

						}
					}
					if(array_key_exists($k,$sepParts) == true){
						$arrNJob[] = array($k,$repair[$k],$model[$k],$repiarType[$k],$charge[$k],$inv1[$k],$inv2[$k],$chargeSys[$k],$sepParts[$k],$cost[$k],$partsQty[$k],$arrTmp2);
					}else{
						$arrNJob[] = array($k,$repair[$k],$model[$k],$repiarType[$k],$charge[$k],$inv1[$k],$inv2[$k],$chargeSys[$k],$cost[$k],$cost[$k],$partsQty[$k],$arrTmp2);
					}
				}
			}
			
			if($checkJobId){
				
				foreach ($checkJobId as $k => $v){
					$count = count($checkparts[$k]);
					$i = 0;
					$arrTmp2 = "";
					foreach($checkparts[$k] as $k2 => $v2){
						$i++;
						if($i != $count){
							$arrTmp2 .= $k2."*".$v2."   ";
						}else{
							$arrTmp2 .= $k2."*".$v2."   ";
						}
					}
					if(array_key_exists($k,$checkSepParts) == true){
						$arrCJob[] = array($k,$checkrepair[$k],$checkmodel[$k],$checkrepiarType[$k],$checkcharge[$k],$checkinv1[$k],"",$checkchargeSys[$k],$checkSepParts[$k],$checkcost[$k],$checkpartsQty[$k],$arrTmp2);
					}else{
						$arrCJob[] = array($k,$checkrepair[$k],$checkmodel[$k],$checkrepiarType[$k],$checkcharge[$k],$checkinv1[$k],"",$checkchargeSys[$k],$checkcost[$k],$checkcost[$k],$checkpartsQty[$k],$arrTmp2);
					}
					
				}	
			}
			
			
			if($pbJobId){
				foreach ($pbJobId as $k => $v){
				
					$count = count($pbparts[$k]);
					$i = 0;
					$arrTmp2 = "";
					foreach($pbparts[$k] as $k2 => $v2){
						$i++;
						if($i != $count){
							$arrTmp2 .= $k2."*".$v2."   ";
						}else{
							$arrTmp2 .= $k2."*".$v2."   ";
						}
						
					}
				
					if(array_key_exists($k,$pbSepParts)== true){
						$arrPJob[] = array($k,$pbrepair[$k],$pbmodel[$k],$pbrepiarType[$k],$pbcharge[$k],$pbinv1[$k],$pbinv2[$k],$pbchargeSys[$k],$pbSepParts[$k],$pbcost[$k],$pbpartsQty[$k],$arrTmp2);
					}else{
						$arrPJob[] = array($k,$pbrepair[$k],$pbmodel[$k],$pbrepiarType[$k],$pbcharge[$k],$pbinv1[$k],$pbinv2[$k],$pbchargeSys[$k],$pbcost[$k],$pbcost[$k],$pbpartsQty[$k],$arrTmp2);
					}
				
				}
			}

			$orderCost = $_POST['orderList'];
			$borrowIn = $_POST['borrowIn'];
			$borrowOut = $_POST['borrowOut'];
			
			$dateBegin = $_POST['date_begin'];
			$dateEnd = $_POST['date_end'];
			$this->view->dateBegin = $dateBegin;
			$this->view->dateEnd = $dateEnd;
			
			
			$exportFileName = "Alex_bonus_".$dateBegin."_".$dateEnd;
		
			$file->exportAlexBonus($arrNJob, $arrCJob, $arrPJob, $exportFileName, $dateBegin, $dateEnd, $orderCost, $borrowIn, $borrowOut);
			echo "<br/><br/>"."<a href=\"http://".SERVER_IP_COMM."/export/alex/{$exportFileName}.xls\" >Download File HERE</a><br/>";
			
			//$this->renderScript("/repairparts/alex-other-deduction.phtml");
		
		
		}

		
		
	}
	
	public function alexInvoiceAction(){
		$stfBonus = new Model_Payroll_Staffbonus(Zend_Registry::get('db_remoteapp'));
		$stf = new Model_DbTable_Roster_Staffinfo(Zend_Registry::get('db_remoteapp'));
		$rStockAd = new Model_DbTable_Pr_Stockmove_Ad(Zend_Registry::get('db_remoteapp'));
		$rProducts = new Model_DbTable_Pr_Prproducts(Zend_Registry::get('db_remoteapp'));
		$mail = new Model_Emailshandler();
		$this->view->check = false;
		$this->view->done = false;
		if(isset($_POST['input'])){

				
				$file = $_FILES['file']['tmp_name'];
				$fileName = $_FILES['file']['name'];
				if(empty ($file)){
					$this->view->errorFlag2 = true;
						
					$this->view->errorMessage = "Please import the file";
					$this->renderScript('/products/importCsv.phtml');
					return false;
				}else{
					$fl = new Model_Fileshandler();
					$uploadFolder = getcwd()."/export/alex/";

					$dateBegin = $_POST['dateBegin'];
					$dateEnd = $_POST['dateEnd'];
					$adNo = $_POST['returnAdNo'];
						
					$adList = $rStockAd->listStockMove(trim($adNo));
					$whReturn = 0;
					$noPriceT = array();
					if($adList){
						
						foreach ($adList as $k3 => $v3){
							if($v3['code_move'] == 5){
							$priceT = $rProducts->getProduct($v3['id_product']);
							if(!empty($priceT['price_t'])&& $priceT['price_t'] != 0){
								$whReturn += $priceT['price_t']*$v3['qty_product']*1.1;
							}else{
								$noPriceT[$v3['id_product']] = $v3;
							}
							}
						}
					}

					if(!empty($noPriceT)){
						foreach ($noPriceT as $k4 => $v4){
							$pDetail = $rProducts->getProduct($k4);
							echo $pDetail['code_product']." has no cost price, please fill in and do again<br/>";
						}
						return false;
					}else{
						if(move_uploaded_file($file,$uploadFolder.$fileName)){
							$fl->reopenAlexBonus($fileName,$whReturn);
						}
	
					
					}
					$this->dateBegin = $dateBegin;
					$this->dateEnd = $dateEnd;
					
					//$mail->sendNormalEmail('office@phonecollection.com.au', 'Test', 'The attached file is alex bonus<br/>Please confirm final amount');
					$mail->sendActionEmail('payroll@phonecollection.com.au', 'Alex Bonus Waiting for Confirm', 'The attached file is alex bonus<br/>Please confirm final amount', getcwd()."/export/alex/", $fileName);
					
					echo "<a href=\"http://".SERVER_IP_COMM."/export/alex/{$fileName}\" >Download File HERE</a><br/>";
				}
					
			
	
		}
		
		if(isset($_POST['upFile'])){
			$file = $_FILES['last_file']['tmp_name'];
			$fileName = $_FILES['last_file']['name'];
			
			if(empty ($file)){
				$this->view->errorFlag2 = true;
			
				$this->view->errorMessage = "Please import the file";
				$this->renderScript('/products/importCsv.phtml');
				return false;
			}else{
				$fl = new Model_Fileshandler();
				$uploadFolder = getcwd()."/export/alex/";
				$period = explode("_", $fileName);
				$dateEnd = explode(".",$period[3]);
					
				$this->view->dateBegin = $period[2];
				$this->view->dateEnd = $dateEnd[0];
				if(move_uploaded_file($file,$uploadFolder.$fileName)){
					$this->view->check = true;
					$finalPay = $fl->getFinalPay($fileName);	
					$this->view->total = $finalPay;
				}
			
			}
		}
		
		if(isset($_POST['confirm'])){
			$dateBegin = $_POST['date_begin'];
			$dateEnd = $_POST['date_end'];
			$totalProfit = $_POST['totalProfit'];
			
			$staffDetail = $stf->getStaffinfo(380);
			if($staffDetail['id_package'] == 1 || $staffDetail['id_package'] == 3 || $staffDetail['id_package'] == 4 || $staffDetail['id_package'] == 6){
						$amtBank = round($totalProfit/1.095,2);
						$amtSuper = round($totalProfit-$amtBank,2);
				
						//$stfBonus->newStaffbonus(380, 1, $dateBegin." - ".$dateEnd." R Bonus", $totalProfit, 0, $amtBank, $amtSuper, $dateBegin, $dateEnd, '0000-00-00', 2, '0000-00-00', null);
			}
			if($staffDetail['id_package'] == 2 || $staffDetail['id_package'] == 5){
				
					//$stfBonus->newStaffbonus(380, 1, $dateBegin." - ".$dateEnd." R Bonus", $totalProfit, $totalProfit, 0, 0, $dateBegin, $dateEnd, '0000-00-00', 1, '0000-00-00', null);				
			}
			
			
			$url = "http://".WEB_IP."/repairparts/repair-wizard-all-summary/date_begin/".$dateBegin."/date_end/".$dateEnd;
			$this->_redirect($url);
			
			
		}
	}
	
	public function repairWizardBonusSummaryAction(){
		error_reporting(E_ALL ^ E_NOTICE);
		$this->view->date = false;
		$cycle = unserialize(BONUS_CYCLE_2015);
		$dateBegin = $this->_getParam("date_begin");
		$dateEnd = $this->_getParam("date_end");
		$shop = unserialize(ARR_RCENTER_REV_MAPPING);
		$shopGroup = unserialize(ARR_SHOP_GROUP);
		$rJobs = new Model_DbTable_Repairjob(Zend_Registry::get('db_remoteapp'));
		$rMove = new Model_DbTable_Pr_Prstockmovement(Zend_Registry::get('db_remoteapp'));
		$rPart = new Model_DbTable_Pr_Prproducts(Zend_Registry::get('db_remoteapp'));
		$rProducts = new Model_DbTable_Pr_Prproducts(Zend_Registry::get('db_remoteapp'));
		$rStatus = new Model_DbTable_Repairstatusrecord(Zend_Registry::get('db_remoteapp'));
		$rBonus = new Model_Payroll_Shopgrouprepairbonusrecord(Zend_Registry::get('db_remoteapp'));
		$this->view->dateBegin = $dateBegin;
		$this->view->dateEnd = $dateEnd;
		
		foreach($cycle as $k2 => $v2){
			if($dateBegin >= $v2[0] && $dateEnd <= $v2[1] ){
				$cycleKey = $k2;
			}
				
		}
		$this->view->cycle = $cycleKey + 1;
		
		if(isset($_POST['submit_rule'])){
			
			$this->view->date = true;
			$dateBegin = $this->_getParam("date_begin");
			$dateEnd = $this->_getParam("date_end");
		
		$barCode = 'PARTSSALES';
		


		$groupRepairBonusSummary = array();
		$shopBonusSummary = array();
		
		foreach ($shop as $key => $val){
			$myQty = 0;
			if($val == 'ADPC' || $val == 'CLPC' || $val == 'WLIC'){
				$invoProducts = Model_Aposinit::initAposInvPro($val);
				$myQty = $invoProducts->getProductSalesQtyByDates($dateBegin, $dateEnd, $barCode);
			}
			$shopBonusSummary[$val] = $myQty;
		}
		
		//get repair parts sell base on APOS
		foreach($shopBonusSummary as $k => $v){
			if($k == 'ADPC' || $k == 'CLPC' || $k == 'WLIC'){
				
				if($k == 'BSPC' || $k == 'BSXP' || $k == 'BSIC'){
					$groupRepairBonusSummary['BAYSIDE GROUP']['parts_apos'] += $v;
				}elseif($k == 'EPPC' || $k == 'EPIC'){
					$groupRepairBonusSummary['EP GROUP']['parts_apos'] += $v;
				}elseif($k == 'WBIC' || $k == 'WBPC'){
					$groupRepairBonusSummary['WB GROUP']['parts_apos'] += $v;
				}elseif($k == 'WGIC' || $k == 'WGPC'){
					$groupRepairBonusSummary['WG GROUP']['parts_apos'] += $v;
				}elseif($k == 'PMIC' || $k == 'PMPC'){
					$groupRepairBonusSummary['PM GROUP']['parts_apos'] += $v;
				}elseif($k == 'CBIC' || $k == 'CBPC'){
					$groupRepairBonusSummary['CB GROUP']['parts_apos'] += $v;
				}
				else{
					$groupRepairBonusSummary[$k]['parts_apos'] += $v;
				}
			}
		}
		//get repair parts sell base on database 
		$invHead = substr($dateBegin,2,2);
		$invHead = "L".$invHead;
		
		$repairpartsDetail = $rMove->listByJobCodeId(2,$invHead,$dateBegin,$dateEnd);
		$list = array();
		foreach($repairpartsDetail as $key => $val){
			$tmpArr = array();
			$shopId = $val['shop_code'];
			$shopName = $shop[$shopId];
			$tmpArr = $val;
			$linePro = 	$rProducts->getProduct($val['id_product']);
			$tmpArr['code_product']= $linePro['code_product'];
			$tmpArr['title_product']= $linePro['title_product'];
			$tmpArr['shop_name'] = $shopName;
			$list[] = $tmpArr;
		}
		
		//d($list);
		foreach($list as $key2 => $val2){
			if($val2['shop_name'] == 'ADPC' || $val2['shop_name'] == 'CLPC' || $val2['shop_name']== 'WLIC'){
				if($val2['shop_name'] == 'BSPC' || $val2['shop_name'] == 'BSXP' || $val2['shop_name'] == 'BSIC'){
					$groupRepairBonusSummary['BAYSIDE GROUP']['parts_database'] += $val2['qty_product'];
				}elseif($val2['shop_name'] == 'EPPC' || $val2['shop_name'] == 'EPIC'){
					$groupRepairBonusSummary['EP GROUP']['parts_database'] += $val2['qty_product'];
				}elseif($val2['shop_name'] == 'WBIC' || $val2['shop_name'] == 'WBPC'){
					$groupRepairBonusSummary['WB GROUP']['parts_database'] += $val2['qty_product'];
				}elseif($val2['shop_name'] == 'WGIC' || $val2['shop_name'] == 'WGPC'){
					$groupRepairBonusSummary['WG GROUP']['parts_database'] += $val2['qty_product'];
				}elseif($val2['shop_name'] == 'PMIC' || $val2['shop_name'] == 'PMPC'){
					$groupRepairBonusSummary['PM GROUP']['parts_database'] += $val2['qty_product'];
				}elseif($val2['shop_name'] == 'CBPC' || $val2['shop_name'] == 'CBIC'){
					$groupRepairBonusSummary['CB GROUP']['parts_database'] += $val2['qty_product'];
				}
				else{
					$groupRepairBonusSummary[$val2['shop_name']]['parts_database'] += $val2['qty_product'];
				}
			}
		}

		$jList = $rJobs->listAllFinishedJobsByDate($dateBegin, $dateEnd);
		//get repair job no.
		foreach($jList as $job){

				$invPro = "";
				$shop =  strtoupper(trim($job["shop_code"]));
				if($shop == 'ADPC' || $shop == 'CLPC' || $shop == 'WLIC'){

				$invPro = Model_Aposinit::initAposInvPro($shop);
				
		
				$invLine = "";
				$invLine2 = "";
				$inv1Count = "";
				$inv2Count = "";
		
				$inv1Disc = 0;
				$inv2Disc = 0;

				$inv1 = substr($job["invoice_no"],-8);
				$inv2 = "";
				$invLine = $invPro->getRepairInvoice("L1".$inv1);
				$inv1Count = count($invPro->getInvoiceProducts("L1".$inv1));
				$inv1Disc = $invPro->getInvoiceDiscount("L1".$inv1);
				if(strlen($job["invoice_no2"]) > 0){
					$inv2 = substr($job["invoice_no2"],-8);
					$invLine2 = $invPro->getRepairInvoice("L1".$inv2);
					$inv2Count = count($invPro->getInvoiceProducts("L1".$inv2));
					$inv2Disc = $invPro->getInvoiceDiscount("L1".$inv2);
				}
				//get repair parts
				$partsRes = $rMove->getPartsSummaryByJobId($job['id_job'],"price_b");

				$wBonus = false;
				$maxBonusFull = 0;
				$maxBonusHalf = 0;
		
				$amtBonusPartsAmt = 1;
				$amtBonusParts = 0;
				$amtBonusService = 0;//2014-07-11
				$perfectBonus = 0;

				foreach($partsRes[0] as $part){
					$amtBonusParts += $amtBonusPartsAmt * $part[1];
					$amtBonusService += $amtBonusPartsAmt * $part[1];
					$perfectBonus += $amtBonusPartsAmt * $part[1];//2014-07-11
					$id = $rPart->getProductID($part[0]);
					$row = $rPart->getProduct($id);
		
					if($row["amt_full_bonus"] > $maxBonusFull){
						$maxBonusFull = $row["amt_full_bonus"];
						$maxBonusHalf = $row["amt_dis_bonus"];
					}
					
				}
		
				$amtBonus = "N/A";

				$repairDis = 0;
				$salesDis = 0;

				if($job["invoice_no2"] == "" ){
		
					if($inv1Count==1){
							$repairDis = $partsRes[1] - $invLine;
					}
					if($inv1Count>1){
							$repairDis = $partsRes[1] - $invLine;
							$salesDis = $inv1Disc;
						}
					}
					else{
		
						if($inv1==$inv2){
								
							if($inv1Count==1){
								$repairDis = $partsRes[1] - $invLine;
							}
							if($inv1Count>1){
								$repairDis = $partsRes[1] - $invLine;
								$salesDis = $inv1Disc;
							}
						}
						else{
		
							$repairDis = $partsRes[1] - $invLine - $invLine2;
							$salesDis = $inv1Disc + $inv2Disc;
						}
							
					}
						
				$bonusAmt = 0;
		
				if( ($repairDis + $salesDis) >0){
					if(isset($_POST['rule_discount'])){ //discount condition
						$amtBonusParts = 0;
					}
				}
		
		
					if( ($repairDis < 5 && $salesDis < 5) || ($repairDis + $salesDis) < 5  ){
							
						$bonusAmt = $maxBonusFull;
						$maxBonusHalf = 0;
							
					}
		
					if(($repairDis >= 5 && $repairDis < 10 && $salesDis >= 5 && $salesDis < 10 ) || (($repairDis + $salesDis) >= 5 && ($repairDis + $salesDis) < 10)  ){
						$bonusAmt = $maxBonusHalf;
						$maxBonusFull = 0;
					}
					if(($repairDis + $salesDis) > 10){
							
						$bonusAmt = 0;
							
						$maxBonusHalf = 0;
						$maxBonusFull = 0;
							
							
					}
		
					$policyArray = $rJobs->bonusRule($job["id_job"]);
		
					if(!$policyArray[0] || !$policyArray[1] ||$job['fix_by_hq']==1){
						$bonusAmt = 0;
						if(isset($_POST['rule_policy'])){ //policy condition
							$amtBonusParts = 0;
						}
						if(isset($_POST['rule_fixhq'])){ //fix by hq condition
							$amtBonusParts = 0;
						}
						$amtBonusService = 0;

						
					}
		
				
				//WHo , what ,finish time , quote , invoices , who record
				$tmpArr = array();
		
				$tmpArr["id_job"] = $job["id_job"];
				$tmpArr["date_start"] =  $job["date_start"];
				$tmpArr["repair_staff"] = $job["repair_staff"];
		
				$arrStaff[] =  $job["repair_staff"];
		
				$tmpArr["shop_code"] = $job["shop_code"];
		
				$arrShop[] = $job["shop_code"];
		
				$tmpArr["mobile_model"] = $job["mobile_model"];
				$tmpArr["quot_price"] = $job["quot_price"];
				$tmpArr["invoice_no"] = $job["invoice_no"];
				$tmpArr["invoice_qty"] =  $inv1Count;
				$tmpArr["invoice_amt"] = $invLine;
				$tmpArr["invoice_no2"] = $job["invoice_no2"];
				$tmpArr["invoice_qty2"] = $inv2Count;
				$tmpArr["invoice_dis"] = $inv1Disc;
				$tmpArr["invoice_dis2"] = $inv2Disc;
				$tmpArr["invoice_amt2"] = $invLine2;
				$tmpArr["staff_record"] = $job["staff_record"];
				$tmpArr["time_record"] = $job["time_record"];
				$tmpArr["part_sum"] = $partsRes;
				$tmpArr["repair_disc"] = $repairDis;
				$tmpArr["sales_disc"] = $salesDis;
				$tmpArr["bonus_amt"] = $bonusAmt;
				$tmpArr["full_bonus_amt"] = $maxBonusFull;
				$tmpArr["dis_bonus_amt"] = $maxBonusHalf;
		
		
				$arrDate[] = $job["time_record"];
		
				$tmpArr['bonus_rule'] = $rJobs->bonusRule($job["id_job"]);
				$tmpArr['bonus_part'] = $amtBonusParts;
				$tmpArr['bonus_service'] = $amtBonusService;
				$tmpArr['perfect_bonus'] = $perfectBonus;
					
				$arrRes[] = $tmpArr;
			}
		}

		array_multisort($arrShop,SORT_ASC,$arrStaff,SORT_ASC,$arrDate,SORT_ASC,$arrRes);

		foreach ($arrRes as $k2 => $v2){
			$rOpen = $rStatus->isJobReopen($v2["id_job"]);
			if(!$rOpen){
				if(strtoupper($v2['shop_code']) != 'WHAL' && strtoupper($v2['shop_code']) != 'WHLU' && strtoupper($v2['shop_code'])!= 'CSIC'){
					if($v2['repair_staff']!= 380){
					if(strtoupper($v2['shop_code']) == 'BSPC' || strtoupper($v2['shop_code']) == 'BSXP' || strtoupper($v2['shop_code']) == 'BSIC'){
						$groupRepairBonusSummary['BAYSIDE GROUP']['service_no'] += $v2['bonus_part'];
						$groupRepairBonusSummary['BAYSIDE GROUP']['perfect_service'] += $v2['perfect_bonus'];

					}elseif(strtoupper($v2['shop_code']) == 'EPPC' || strtoupper($v2['shop_code']) == 'EPIC'){
						$groupRepairBonusSummary['EP GROUP']['service_no'] += $v2['bonus_part'];
						$groupRepairBonusSummary['EP GROUP']['perfect_service'] += $v2['perfect_bonus'];

					}elseif(strtoupper($v2['shop_code']) == 'WBIC' || strtoupper($v2['shop_code']) == 'WBPC'){
						$groupRepairBonusSummary['WB GROUP']['service_no'] += $v2['bonus_part'];
						$groupRepairBonusSummary['WB GROUP']['perfect_service'] += $v2['perfect_bonus'];

					}elseif(strtoupper($v2['shop_code']) == 'WGIC' || strtoupper($v2['shop_code']) == 'WGPC'){
						$groupRepairBonusSummary['WG GROUP']['service_no'] += $v2['bonus_part'];
						$groupRepairBonusSummary['WG GROUP']['perfect_service'] += $v2['perfect_bonus'];

					}elseif(strtoupper($v2['shop_code']) == 'PMIC' || strtoupper($v2['shop_code']) == 'PMPC'){
						$groupRepairBonusSummary['PM GROUP']['service_no'] += $v2['bonus_part'];
						$groupRepairBonusSummary['PM GROUP']['perfect_service'] += $v2['perfect_bonus'];

					}
					elseif(strtoupper($v2['shop_code']) == 'CBIC' || strtoupper($v2['shop_code']) == 'CBPC'){
						$groupRepairBonusSummary['CB GROUP']['service_no'] += $v2['bonus_part'];
						$groupRepairBonusSummary['CB GROUP']['perfect_service'] += $v2['perfect_bonus'];
					
					}				
					else{
						$groupRepairBonusSummary[strtoupper($v2['shop_code'])]['service_no'] += $v2['bonus_part'];
						$groupRepairBonusSummary[strtoupper($v2['shop_code'])]['perfect_service'] += $v2['perfect_bonus'];
						
					}
					}
				}
			}
		}

		ksort($groupRepairBonusSummary);
		
		$this->view->list = $groupRepairBonusSummary;
		}
	//	d($groupRepairBonusSummary);
		if(isset($_POST['calculate'])){
			
			if(!empty($_POST['shop_id'])){
				foreach($_POST['shop_id'] as $k => $v){
					$shopCode = $shopGroup[$k];
					$total = round(($_POST['service_value'][$k] * $_POST['multi_no'][$k]),2);
					$bonus = $rBonus->getRepairBonusByShopIdDate($k, $dateBegin, $dateEnd);
					if(!$bonus){
						$rBonus->addBonusRecord($k, $shopCode, $total, $dateBegin, $dateEnd, 0);
					}else{
						$rBonus->updateBonusRecord($bonus['id'], $k, $shopCode, $total, $dateBegin, $dateEnd, 0);
					}
				}

			}
			
			$url = "/repairparts/repair-wizard-add-stock-lost/date_begin/".$dateBegin."/date_end/".$dateEnd."/next/yes";
			$this->_redirect($url); 
		}
		
	}
					
	public function repairWizardAddStockLostAction(){
		$shopList = unserialize(ARR_SHOP_GROUP);
		$periodBegin = $this->_getParam("date_begin");
		$periodEnd = $this->_getParam("date_end");
		$cycle = unserialize(BONUS_CYCLE_2015);
		$this->view->dateBegin = $periodBegin;
		$this->view->dateEnd = $periodEnd;
		$nextCheck = $this->_getParam("next");
		
		foreach($cycle as $k2 => $v2){
			if($periodBegin >= $v2[0] && $periodEnd <= $v2[1] ){
				$cycleKey = $k2;
			}
				
		}
		$this->view->cycle = $cycleKey + 1;
		if($nextCheck == 'yes'){
			$check = true;
			$this->view->nextCheck = $check;
		}
		
		
		$bos = new Model_Payroll_Shopgroupbonus(Zend_Registry::get('db_remoteapp'));
		
		$ShopLost = array();
		foreach($shopList as $k => $v){
			if($k == 1 || $k == 6 || $k == 17){
			$tmpArr = array();
			$stockLost = $bos->getStockLostByShopIdByType($k, $periodBegin, $periodEnd,8);
			$tmpArr['shop_id'] = $k;
			$tmpArr['shop_code']  = $v;
			$tmpArr['before_stocklost'] = $stockLost['amt_total_bonus'];
			$ShopLost[] = $tmpArr;
			}
		}
		
		$this->view->stocklost = $ShopLost;
		
		if(isset($_POST['button'])){
			$newStockLost = array();
	
			foreach($_POST['shop_code'] as $key => $val){
				$bosCheck = $bos->getStockLostByShopIdByType($key, $periodBegin, $periodEnd, 7);
			
				if(!$bosCheck){
					$bos->newShopbonus($key, 7, $periodBegin." current Repair lost", $_POST['current_stocklost'][$key], $_POST['current_stocklost'][$key], 0, 0, $periodBegin, $periodEnd, '0000-00-00', 0, '1111-01-01', 'none',$val);
				}else{
					$bos->updateAdjStockLost($bosCheck['id_bonus'], $_POST['current_stocklost'][$key], $_POST['current_stocklost'][$key]);
				}

				$tmpArr2 = array();
				$bfstockLost = $bos->getStockLostByShopIdByType($key, $periodBegin, $periodEnd,8);
				$currentStockLost = $bos->getStockLostByShopIdByType($key, $periodBegin, $periodEnd, 7);
				$tmpArr2['shop_id'] = $key;
				$tmpArr2['shop_code']  = $val;
				$tmpArr2['before_stocklost'] = $bfstockLost['amt_total_bonus'];
				$tmpArr2['current_stocklost'] = $currentStockLost['amt_total_bonus'];
				$newStockLost[] = $tmpArr2;
			}
				
			$this->view->newStockLost = $newStockLost;
				
			echo "Add Repair stock lost success";
		}
		
		if(isset($_POST['next'])){
			foreach($_POST['shop_code'] as $key => $val){
				$bosCheck = $bos->getStockLostByShopIdByType($key, $periodBegin, $periodEnd, 9);
				if(!$bosCheck){
					$bos->newShopbonus($key, 9, $periodBegin." adjusted Repair lost", $_POST['adj_total'][$key], $_POST['adj_total'][$key], 0, 0, $periodBegin, $periodEnd, '0000-00-00', 0, '1111-01-01', 'none',$val);
				}else{
					$bos->updateAdjStockLost($bosCheck['id_bonus'], $_POST['adj_total'][$key], $_POST['adj_total'][$key]);
				}
			}
			$url = "/repairparts/repair-wizard-confirm-total/date_begin/".$periodBegin."/date_end/".$periodEnd."/next/yes";
			$this->_redirect($url);
		}

	}
	
	public function repairWizardConfirmTotalAction(){
		$shopGroup = unserialize(ARR_SHOP_GROUP);
		$bos = new Model_Payroll_Shopgroupbonus(Zend_Registry::get('db_remoteapp'));
		$carryBonus = new Model_Payroll_Shopgroupcarrybonus(Zend_Registry::get('db_remoteapp'));
		$bonusRecord = new Model_Payroll_Shopgrouprepairbonusrecord(Zend_Registry::get('db_remoteapp'));
		$periodBegin = $this->_getParam("date_begin");
		$periodEnd = $this->_getParam("date_end");
		$cycle = unserialize(BONUS_CYCLE_2015);
		$this->view->dateBegin = $periodBegin;
		$this->view->dateEnd = $periodEnd;
		$nextCheck = $this->_getParam("next");
		
		foreach($cycle as $k2 => $v2){
			if($periodBegin >= $v2[0] && $periodEnd <= $v2[1] ){
				$cycleKey = $k2;
			}		
		}
		if($nextCheck == 'yes'){
			$check = true;
			$this->view->nextCheck = $check;
		}
		$this->view->cycle = $cycleKey + 1;
		
			$nextCycleBegin = $cycle[$cycleKey + 1][0];
			$nextCycleEnd = $cycle[$cycleKey + 1][1];
			
		$bonusList = array();
		
		
		
		foreach($shopGroup as $key => $val){
			if($key == 1 || $key == 6 || $key == 17){
			$tmpArr2 = array();
			$adjStockLost = $bos->getStockLostByShopIdByType($key, $periodBegin, $periodEnd,9);
				
			$tmpArr2['id_shop'] = $key;
			$tmpArr2['shop_code']  = $val;
			$tmpArr2['adj_stocklost'] = $adjStockLost['amt_total_bonus'];
			$totalStockLost = $adjStockLost['amt_total_bonus'];
			$tmpforwardBonus = $carryBonus->getCarryBonusByShopIdDateType($key, $periodBegin, $periodEnd,2);
			if(!$tmpforwardBonus){
				$forwardBonus = 0;
			}else{
				$forwardBonus = $tmpforwardBonus['carry_bonus'];
			}
			$tmpArr2['carry_bonus']= $forwardBonus;
			//get repair bonus
			$bonus = $bonusRecord->getRepairBonusByShopIdDate($key, $periodBegin, $periodEnd);
			$tmpArr2['total_stock_lost'] = $totalStockLost;
			
			$finalBonus = $bonus['final_bonus'] + $forwardBonus;
			$exBonus = round(($bonus['final_bonus'] * 0.25),2);
			$tmpArr2['final_bonus'] = $bonus['final_bonus'];
			$tmpArr2['ex_bonus'] = $exBonus;
				
			if($exBonus == 0){
				$tmpArr2['net_bonus']  = $finalBonus;
				$tmpArr2['carry_stock_lost'] = $totalStockLost;
			}elseif ($totalStockLost >= 0){
				$tmpArr2['net_bonus']  = $finalBonus + $exBonus;
				$tmpArr2['carry_stock_lost'] = $totalStockLost;
			}elseif(($totalStockLost+$exBonus)>=0){
				$tmpArr2['net_bonus']  = $totalStockLost+$finalBonus+$exBonus;
				$tmpArr2['carry_stock_lost'] = 0;
			}elseif(($totalStockLost+$exBonus)<0){
				$tmpArr2['net_bonus']  = $finalBonus;
				$tmpArr2['carry_stock_lost'] = $totalStockLost+$exBonus;
			}

			$bonusList[] = $tmpArr2;
			}
		}
		$this->view->bonusList = $bonusList;
		if(isset($_POST['submit'])){
		
			foreach($_POST['shop_code'] as $k => $v){
				//update net repair bonus
				$bonusRecord->updateNetBonus($k, $periodBegin, $periodEnd, $_POST['net_bonus'][$k]);
				//add carry repair stock lost
				
				if($_POST['carry_stocklost'][$k] < 0){
					$bosCheck = $bos->getStockLostByShopByType($v, $nextCycleBegin, $nextCycleEnd, 8);
					if(!$bosCheck){
						$bos->newShopbonus($k, 8, $periodBegin."carryforwardlost", $_POST['carry_stocklost'][$k], $_POST['carry_stocklost'][$k], 0, 0, $nextCycleBegin, $nextCycleEnd, '0000-00-00', 0, '0000-00-00', 'none',$v);
					}else{
						$bos->updateAdjStockLost($bosCheck['id_bonus'], $_POST['carry_stocklost'][$k], $_POST['carry_stocklost'][$k]);
					}
				}else{
					$bos->newShopbonus($k, 8, $periodBegin."carryforwardlost", 0, 0, 0, 0, $nextCycleBegin, $nextCycleEnd, '0000-00-00', 0, '0000-00-00', 'none',$v);
				}
			}
			$bonusList2 = array();
			foreach($shopGroup as $k2 => $v2){
				if($k2 == 1 || $k2 == 6 || $k2 == 17){
				$adjStockLost = $bos->getStockLostByShopIdByType($k2, $periodBegin, $periodEnd,9);
				$bonusDetail = $bonusRecord->getRepairBonusByShopIdDate($k2, $periodBegin, $periodEnd);
				$carryStock = $bos->getStockLostByShopIdByType($k2, $nextCycleBegin, $nextCycleEnd,8);
				$cBonus = $carryBonus->getCarryRepairBonusByShopIdDate($k2, $periodBegin, $periodEnd);
				
				
				$exBonus = round(($bonusDetail['final_bonus'] * 0.25),2);
				
				$tmpArr3['id_shop'] = $k2;
				$tmpArr3['shop_code']  = $v2;
				$tmpArr3['adj_stocklost'] = $adjStockLost['amt_total_bonus'];
				$tmpArr3['ex_bonus'] = $exBonus;
				$tmpArr3['final_bonus'] = $bonusDetail['final_bonus'];
				$tmpArr3['carry_bonus']= $cBonus['carry_bonus'];
				$tmpArr3['net_bonus'] = $bonusDetail['net_bonus'];
				$tmpArr3['carry_stock_lost'] = $carryStock['amt_total_bonus'];
				$bonusList2[] = $tmpArr3;
				}
			
			}
			$this->view->bonusList = $bonusList2;
		
			echo "Confirm success";
		
		}
		
		
		
	}
	public function repairWizardDistributionAction(){
		error_reporting(E_ALL ^ E_NOTICE);
		$dateBegin = $this->_getParam("date_begin");
		$dateEnd = $this->_getParam("date_end");
		$cycle = unserialize(BONUS_CYCLE_2015);
		$barCode = 'PARTSSALES';
		$shop = unserialize(ARR_RCENTER_REV_MAPPING);
		$shopGroup = unserialize(ARR_SHOP_GROUP);
		$shopList = unserialize(ARR_GROUP_SHOPS);
		$rJobs = new Model_DbTable_Repairjob(Zend_Registry::get('db_remoteapp'));
		$rMove = new Model_DbTable_Pr_Prstockmovement(Zend_Registry::get('db_remoteapp'));
		$rPart = new Model_DbTable_Pr_Prproducts(Zend_Registry::get('db_remoteapp'));
		$rProducts = new Model_DbTable_Pr_Prproducts(Zend_Registry::get('db_remoteapp'));
		$rStatus = new Model_DbTable_Repairstatusrecord(Zend_Registry::get('db_remoteapp'));
		$ts = new Model_DbTable_Roster_Timesheet(Zend_Registry::get('db_remoteapp'));
		$stInfo = new Model_DbTable_Roster_Staffinfo(Zend_Registry::get('db_remoteapp'));
		$stfBonus = new Model_Payroll_Staffbonus(Zend_Registry::get('db_remoteapp'));
		$forwardBonus = new Model_Payroll_Shopgroupcarrybonus(Zend_Registry::get('db_remoteapp'));
		$rBonus = new Model_Payroll_Shopgrouprepairbonusrecord(Zend_Registry::get('db_remoteapp'));
		$this->view->dateBegin = $dateBegin;
		$this->view->dateEnd = $dateEnd;
		$nextCheck = $this->_getParam("next");
		foreach($cycle as $k2 => $v2){
			if($dateBegin >= $v2[0] && $dateEnd <= $v2[1] ){
				$cycleKey = $k2 +1;
			}
		
		}
		if($nextCheck == 'yes'){
			$check = true;
			$this->view->nextCheck = $check;
		}
		$this->view->cycle = $cycleKey;
		
		$nextCycleBegin = $cycle[$cycleKey][0];
		$nextCycleEnd = $cycle[$cycleKey][1];
		
		//if(isset($_POST['submit_rule'])){

			$dateBegin = $this->_getParam("date_begin");
			$dateEnd = $this->_getParam("date_end");
		
			
		
		
			$groupRepairBonusSummary = array();
			$staffCost = array();
			$jList = $rJobs->listAllFinishedJobsByDate($dateBegin, $dateEnd);
		
			//get repair job no.
			foreach($jList as $job){
				$stJob = $rStatus->getLastStatus($job["id_job"]);
		
				if($stJob[0]["id_status"] == 90 ){
					$invPro = "";
					$shop =  strtoupper(trim($job["shop_code"]));
					
					if($shop == 'ADPC'|| $shop == 'CLPC' || $shop == 'WLIC'){
		
					$invLine = "";
					$invLine2 = "";
					$inv1Count = "";
					$inv2Count = "";
		
					$inv1Disc = 0;
					$inv2Disc = 0;
		
					$inv1 = substr($job["invoice_no"],-8);
					$inv2 = "";

					if(strlen($job["invoice_no2"]) > 0){
						$inv2 = substr($job["invoice_no2"],-8);
					}
					//get repair parts
					$partsRes = $rMove->getPartsSummaryByJobId($job['id_job'],"price_b");
		
					$wBonus = false;
					$maxBonusFull = 0;
					$maxBonusHalf = 0;
		
					$amtBonusPartsAmt = 1;
					$amtBonusParts = 0;
					$amtBonusService = 0;//2014-07-11
					$perfectBonus = 0;
		
	
					$amtBonusParts = $partsRes[1];
					$amtBonusService = $partsRes[1];
					$perfectBonus = $partsRes[1];//2014-07-11

					$amtBonus = "N/A";
					$repairDis = 0;
					$salesDis = 0;

					//WHo , what ,finish time , quote , invoices , who record
					$tmpArr = array();
		
					$tmpArr["id_job"] = $job["id_job"];
					$tmpArr["date_start"] =  $job["date_start"];
					$tmpArr["repair_staff"] = $job["repair_staff"];
		
					$arrStaff[] =  $job["repair_staff"];
		
					$tmpArr["shop_code"] = $job["shop_code"];
		
					$arrShop[] = $job["shop_code"];
		
					$tmpArr["mobile_model"] = $job["mobile_model"];
					$tmpArr["quot_price"] = $job["quot_price"];
					$tmpArr["invoice_no"] = $job["invoice_no"];
					$tmpArr["invoice_qty"] =  $inv1Count;
					$tmpArr["invoice_amt"] = $invLine;
					$tmpArr["invoice_no2"] = $job["invoice_no2"];
					$tmpArr["invoice_qty2"] = $inv2Count;
					$tmpArr["invoice_dis"] = $inv1Disc;
					$tmpArr["invoice_dis2"] = $inv2Disc;
					$tmpArr["invoice_amt2"] = $invLine2;
					$tmpArr["staff_record"] = $job["staff_record"];
					$tmpArr["time_record"] = $job["time_record"];
					$tmpArr["part_sum"] = $partsRes;
					$tmpArr["w_bonus"] = $wBonus;
					$tmpArr["repair_disc"] = $repairDis;
					$tmpArr["sales_disc"] = $salesDis;
					$tmpArr["full_bonus_amt"] = $maxBonusFull;
					$tmpArr["dis_bonus_amt"] = $maxBonusHalf;
		
		
					$arrDate[] = $job["time_record"];
		
					$tmpArr['bonus_rule'] = $rJobs->bonusRule($job["id_job"]);
					$tmpArr['bonus_part'] = $amtBonusParts;
					$tmpArr['bonus_service'] = $amtBonusService;
					$tmpArr['perfect_bonus'] = $perfectBonus;
						
					$arrRes[] = $tmpArr;
					}
				}
			}
			array_multisort($arrShop,SORT_ASC,$arrStaff,SORT_ASC,$arrDate,SORT_ASC,$arrRes);
		
			foreach ($arrRes as $k2 => $v2){
				$rOpen = $rStatus->isJobReopen($v2["id_job"]);
				$totalCost = 0;
				if(!$rOpen){
					if(strtoupper($v2['shop_code']) == 'ADPC' && strtoupper($v2['shop_code']) == 'CLPC' && strtoupper($v2['shop_code'])!= 'WLIC'){
						if($v2['repair_staff']!= 380){
						if(strtoupper($v2['shop_code']) == 'BSPC' || strtoupper($v2['shop_code']) == 'BSXP' || strtoupper($v2['shop_code']) == 'BSIC'){
							$groupRepairBonusSummary['BAYSIDE GROUP'][$v2['repair_staff']] += $v2['bonus_service'];
							$totalCost = $v2["part_sum"][1];
							
							$staffCost['BAYSIDE GROUP'][$v2['repair_staff']] += $totalCost;
						}elseif(strtoupper($v2['shop_code']) == 'EPPC' || strtoupper($v2['shop_code']) == 'EPIC'){
							$totalCost = $v2["part_sum"][1];
							$groupRepairBonusSummary['EP GROUP'][$v2['repair_staff']] += $v2['bonus_service'];
							$staffCost['EP GROUP'][$v2['repair_staff']] += $totalCost;
						}elseif(strtoupper($v2['shop_code']) == 'WBIC' || strtoupper($v2['shop_code']) == 'WBPC'){
							$totalCost = $v2["part_sum"][1];
							$groupRepairBonusSummary['WB GROUP'][$v2['repair_staff']] += $v2['bonus_service'];
							$staffCost['WB GROUP'][$v2['repair_staff']] += $totalCost;
						}elseif(strtoupper($v2['shop_code']) == 'WGIC' || strtoupper($v2['shop_code']) == 'WGPC'){
							$totalCost = $v2["part_sum"][1];
							$groupRepairBonusSummary['WG GROUP'][$v2['repair_staff']] += $v2['bonus_service'];
							$staffCost['WG GROUP'][$v2['repair_staff']] += $totalCost;
						}elseif(strtoupper($v2['shop_code']) == 'PMIC' || strtoupper($v2['shop_code']) == 'PMPC'){
							$totalCost = $v2["part_sum"][1];
							$groupRepairBonusSummary['PM GROUP'][$v2['repair_staff']] += $v2['bonus_service'];
							$staffCost['PM GROUP'][$v2['repair_staff']] += $totalCost;
						}elseif(strtoupper($v2['shop_code']) == 'CBIC' || strtoupper($v2['shop_code']) == 'CBPC'){
							$totalCost = $v2["part_sum"][1];
							$groupRepairBonusSummary['CB GROUP'][$v2['repair_staff']] += $v2['bonus_service'];
							$staffCost['CB GROUP'][$v2['repair_staff']] += $totalCost;
						}else{
							$totalCost = $v2["part_sum"][1];
							$groupRepairBonusSummary[strtoupper($v2['shop_code'])][$v2['repair_staff']] += $v2['bonus_service'];
							$staffCost[strtoupper($v2['shop_code'])][$v2['repair_staff']] += $totalCost;
						}
						}
					}
				}
			}
		
			ksort($groupRepairBonusSummary);
			//dd($groupRepairBonusSummary);
			
			foreach($groupRepairBonusSummary as $k => $v){
				$groupKey = array_search($k,$shopGroup); //get shopgroup id
				$arrShops = $shopList[$groupKey];//get group shop list
				$repairBonus = $rBonus->getRepairBonusByShopIdDate($groupKey, $dateBegin, $dateEnd);
				$arrStaff = array();
				$shopStaffList = array();
				$finalList = array();
				arsort($v); 
				$firstStaff =array_slice($v,0,1,true); //get first staff
				$secondStaff = array_slice($v,1,2,true); //get second staff
				$firstStaffValue =array_slice($v,0,1); //get first staff
				$secondStaffValue = array_slice($v,1,2); //get second staff

				if($firstStaffValue[0] == $secondStaffValue[0]){
					if($staffCost[$k][key($firstStaff)] < $staffCost[$k][key($secondStaff)]){
						$firstStaff = array_slice($v,1,2,true); //get first staff
						$secondStaff = array_slice($v,0,1,true); //get second staff
					}
				}
				
				$restStaff = array();
				foreach ($v as $k3 => $v3){
					if($k3 != key($firstStaff) && $k3 != key($secondStaff)){
						$restStaff[] = (string)$k3;
					}
				}
				foreach($arrShops as $val){ //list all staff working in thie period in this shop
					$tsList = $ts->listConfirmedShiftByDateByShop($val, $dateBegin, $dateEnd);
					foreach($tsList as $line){
						if($line['confirm_shift_end'] - $line['confirm_shift_begin'] != 0){
							$arrStaff[$groupKey][] = $line['id_staff'];
						}
					}
				}
				$arrStaff = array_unique($arrStaff[$groupKey]);
				$tmpStfArr = array();
				foreach($arrStaff as $staff){
					if($staff != key($firstStaff) && $staff != key($secondStaff)){
						$tmpStfArr[] = $staff;
					}
				}
				$tmpList = array_merge($tmpStfArr,$restStaff);
				$tmpList2 = array_unique($tmpList);
				foreach($tmpList2 as $k4 => $v4){
					if(is_numeric($v4)){
						$stLine = $stInfo->getStaffinfo($v4);
 						if($stLine['position_status'] != 7 && $stLine['position_status'] != 99 && $stLine['position_status'] != 8 && $stLine['id_staff'] != 380){
 							$finalList[] = $v4;
 						}
					}
				}
				
				$groupRepairBonusSummary[$k]['listone'] = key($firstStaff);
				$groupRepairBonusSummary[$k]['listtwo'] = key($secondStaff);
				$groupRepairBonusSummary[$k]['listrest'] = $finalList;
				$groupRepairBonusSummary[$k]['repair_bonus'] = $repairBonus['net_bonus'];
			}
			
			//dd($groupRepairBonusSummary);
			//d($staffCost);
			$this->view->list = $groupRepairBonusSummary;
	//	}
		
		if(isset($_POST['submit'])){
			$repairBonusList = array();
			$carryRepairBonus = array();
			$stDetail = new Model_DbTable_Roster_Stafflogindetail(Zend_Registry::get('db_remoteapp'));
			foreach($_POST['netBonus'] as $shop => $value){
				if($value > 0){
				echo "SHOP:".$shop." Total AMT:".$value."<br/>";
				$arrFirst = round(($value * 0.4),2);
				$arrSecond = round(($value * 0.3),2);
				$arrRest = round(($value * 0.3),2);
					if(!empty($_POST['checkbox1'][$shop])){
						foreach($_POST['checkbox1'][$shop] as $k5 => $v5){
							$repairBonusList[$v5] += $arrFirst;
							$stLine = $stDetail->getDetail($v5);
							echo 'Staff: '.$stLine['ni']. " get 1st 40% Bonus ". $arrFirst."<br/>";
						}
					}else{
						echo "No 1st Staff Bonus ". $arrFirst ." will carry forward."."<br/>";
						$carryRepairBonus[$shop] += $arrFirst;
					}
					if(!empty($_POST['checkbox2'][$shop])){
						foreach($_POST['checkbox2'][$shop] as $k5 => $v5){
							$repairBonusList[$v5] += $arrSecond;
							$stLine = $stDetail->getDetail($v5);
							echo 'Staff: '.$stLine['ni']. " get 2nd 30% Bonus ". $arrSecond."<br/>";
						}
					}else{
						echo "No 2nd Staff Bonus ". $arrSecond ." will carry forward."."<br/>";
						$carryRepairBonus[$shop] += $arrSecond;
					}
					if(!empty($_POST['checkboxRest'][$shop])){
						foreach($_POST['checkboxRest'][$shop] as $k5 => $v5){
							$stLine = $stDetail->getDetail($v5);
							$repairBonusList[$v5] += round($arrRest/(count($_POST['allListRest'][$shop])),2);
							echo 'Staff: '.$stLine['ni']. " get rest 30% Bonus ". round($arrRest/(count($_POST['allListRest'][$shop])),2)."<br/>";
						}
					}else{
						echo "No Rest Staff Bonus ". $arrRest ." will carry forward."."<br/>";
						$carryRepairBonus[$shop] += $arrRest;
					}
					echo "<br/>";
				}
			}

			
			foreach($repairBonusList as $stfId => $bonus){
				$staffDetail = $stInfo->getStaffinfo($stfId);
				//pay by bank
				if($staffDetail['id_package'] == 1 || $staffDetail['id_package'] == 3 || $staffDetail['id_package'] == 4 || $staffDetail['id_package'] == 6 || $staffDetail['id_package'] == 7 || $staffDetail['id_package'] == 8){
					$amtBank = round($bonus/1.095,2);
					$amtSuper = round($bonus - $amtBank,2);
					$stfBonus->newStaffbonus($stfId, 1, "Cycle".$cycleKey." Repair Bonus", $bonus, 0, $amtBank, $amtSuper, $dateBegin, $dateEnd, '0000-00-00', 2, '1111-00-00', null);
				}
				//pay by cash
				if($staffDetail['id_package'] == 2 || $staffDetail['id_package'] == 5){
				
					$stfBonus->newStaffbonus($stfId, 1, "Cycle".$cycleKey." Repair Bonus", $bonus, $bonus, 0, 0, $dateBegin, $dateEnd, '0000-00-00', 1, '1111-00-00', null);
				}
			}
			foreach($carryRepairBonus as $k4 => $v4){
				$key = array_search($k4, $shopGroup);
				$checkForwardBonuse = $forwardBonus->getCarryRepairBonusByShopIdDate($key, $nextCycleBegin, $nextCycleEnd);
				if(!$checkForwardBonuse){
					$forwardBonus->addCarryBonus($key, $k4, 2 , $v4, $nextCycleBegin, $nextCycleEnd);
				}
			}
		}
		
	}
	
	public function repairWizardConfirmAction(){
		$bos = new Model_Payroll_Shopgroupbonus();
		$bonusRecord = new Model_Payroll_Shopgroupbonusrecord();
		$carryBonus = new Model_Payroll_Shopgroupcarrybonus();
		$stf = new Model_Payroll_Staffbonus();
		$shopGroup = unserialize(ARR_SHOP_GROUP);
		$cycle = unserialize(BONUS_CYCLE_2015);
		$payrollCycle = unserialize(PAYROLL_CYCLE_SELECT);
		$nextCheck = $this->_getParam("next");
		$periodBegin = $this->_getParam("date_begin");
		$periodEnd = $this->_getParam("date_end");
		if($nextCheck == 'yes'){
			$check = true;
			$this->view->nextCheck = $check;
		}
		$this->view->dateStart = $periodBegin;
		$this->view->dateEnd = $periodEnd;
		
		foreach($cycle as $k2 => $v2){
			if($periodBegin >= $v2[0] && $periodEnd <= $v2[1] ){
				$cycleKey = $k2;
			}
		
		}
		$this->view->cycle = $cycleKey + 1;
		$this->view->dateStart = $periodBegin;
		$this->view->dateEnd = $periodEnd;
		
		if(isset($_POST['confirm'])){
			$stfList = $stf->listPeriodRepairBonus($periodBegin,$periodEnd);
				
			foreach($stfList as $k => $v){
				$paydate = $_POST['payroll_date'];
				$stf->updateDisplayPayDate($v['id_bonus'], $_POST['display_date'], $payrollCycle[$paydate][1]);
			}
				
			$url = "http://".WEB_IP."/repairparts/repair-wizard-all-summary/date_begin/".$periodBegin."/date_end/".$periodEnd;
			$this->_redirect($url);
		}
	}
	
	public function repairWizardAllSummaryAction(){
		$bos = new Model_Payroll_Shopgroupbonus();
		$bonusRecord = new Model_Payroll_Shopgroupbonusrecord();
		$carryBonus = new Model_Payroll_Shopgroupcarrybonus();
		$stf = new Model_Payroll_Staffbonus();
		$shopGroup = unserialize(ARR_SHOP_GROUP);
		$cycle = unserialize(BONUS_CYCLE_2015);
		$payrollCycle = unserialize(PAYROLL_CYCLE_SELECT);
		$nextCheck = $this->_getParam("next");
		$periodBegin = $this->_getParam("date_begin");
		$periodEnd = $this->_getParam("date_end");
		if($nextCheck == 'yes'){
			$check = true;
			$this->view->nextCheck = $check;
		}
		$this->view->dateStart = $periodBegin;
		$this->view->dateEnd = $periodEnd;
		
		foreach($cycle as $k2 => $v2){
			if($periodBegin >= $v2[0] && $periodEnd <= $v2[1] ){
				$cycleKey = $k2;
			}
		
		}
		$this->view->cycle = $cycleKey + 1;
		$this->view->dateStart = $periodBegin;
		$this->view->dateEnd = $periodEnd;
		
		
		if(isset($_POST['saveChange'])){
			foreach($_POST['saveChange'] as $k => $v){
				if(!empty($_POST['check_delay'])){	//update pay_date
					foreach($_POST['check_delay'][$k] as $k2 => $v2){
						$idBonus = $k2;
						$datePay = $_POST['date_delay'][$k][$k2];
						$stf->updatePaymethodStatusDate($idBonus, $payrollCycle[$datePay][1]);
		
					}
				}
				if(!empty($_POST['check_release'])){ //update display_date
					foreach($_POST['check_release'][$k] as $k2 => $v2){
						$idBonus = $k2;
						$dateRelease = $_POST['date_release'][$k][$k2];
						$stf->updateDisplayStatusDate($idBonus, $dateRelease);
					}
				}
				if(!empty($_POST['check_cancel'])){  //cancel bonus
					foreach($_POST['check_cancel'][$k] as $k2 => $v2){
						$idBonus = $k2;
						$cancelReason = $_POST['cancel_reason'][$k][$k2];
						$stf->updateCancelStatus($idBonus, $cancelReason);
		
					}
				}
				if(!empty($_POST['pay_date_check'])){  //update confirm_date
					foreach($_POST['pay_date_check'][$k] as $k2 => $v2){
						$idBonus = $k2;
						$datePaid = $_POST['pay_date'][$k][$k2];
						$stf->updateConfirmPaydate($idBonus, $payrollCycle[$datePaid][1]);
					}
				}
				
				if(!empty($_POST['add_comment'])){ //update hold comment
					foreach($_POST['add_comment'][$k] as $k2 => $v2){
						$idBonus = $k2;
						$comment = $_POST['comment'][$k];
						$stf->updateHoldReason($idBonus, $comment);
					}
				}
			}
		}
		
	}
	
	public function repairWizardNewRuleAction(){
		$dateBegin = $this->_getParam("date_begin");
		$dateEnd = $this->_getParam("date_end");
		$this->view->dateBegin = $dateBegin;
		$this->view->dateEnd = $dateEnd;
	}
	
	public function repairWizardPreRbonusAction(){
		$cycle = unserialize(BONUS_CYCLE_2015);
		$dateBegin = $this->_getParam("date_begin");
		$dateEnd = $this->_getParam("date_end");
		$shopGroup = unserialize(ARR_SHOP_GROUP);
		$rJobs = new Model_DbTable_Repairjob(Zend_Registry::get('db_remoteapp'));

		
		
		if(isset($_POST['submit'])){
			$dateBegin = $_POST['date_begin'];
			$dateEnd = $_POST['date_end'];
			
			$jList = $rJobs->listAllFinishedJobsByDate($dateBegin, $dateEnd);
	
		//get repair job no.
			foreach($jList as $job){
		
				$invPro = "";
				//if($job['repair_staff'] == 380){
				
				$shop =  strtoupper(trim($job["shop_code"]));
				if($shop == 'WHAL'){
					$invPro = Model_Aposinitnew::initAposInvPro('FGIC');
				}else{
					$invPro = Model_Aposinitnew::initAposInvPro($shop);
				}
		
				$invLine = "";
				$invLine2 = "";
	
				$inv1 = substr($job["invoice_no"],-8);
				$inv2 = "";
				if(!empty($inv1)){
					$invLine = $invPro->getRepairInvoiceTotal("L1".$inv1,$job['quot_price'],"C1".$inv1);
				}
				
				if(strlen($job["invoice_no2"]) > 0){
					$inv2 = substr($job["invoice_no2"],-8);
					$invLine2 = $invPro->getRepairInvoiceTotal("L1".$inv2,$job['quot_price'],"C1".$inv2);

				}
				
					if($invLine){
						$rJobs->updateInvoice($job['id_job'], $job["invoice_no"],$invLine);
					}
					if($invLine2){
						$rJobs->updateInvoice2($job['id_job'], $job["invoice_no2"],$invLine2);
					}
					echo $job['id_job']." Inv:".$job['invoice_no']." APOS:".$invLine."<br/>";
				}
				
			//}
			
			echo "success";
		}
	}
	
	public function repairWizardMainAction(){
		$bonuscycle = unserialize(BONUS_CYCLE_2015);
		$this->view->cycle = $bonuscycle;
		
		if(isset($_POST['next'])){
			$cycle = explode(':', $_POST['cycle']);
			foreach($bonuscycle as $k => $v){
				if($cycle[0]== $v[0] && $cycle[1] == $v[1]){
					$mycycle = $k + 1;
				}
			}

			if($_POST['pay_method'] == 1){
				$url = "/repairparts/repair-wizard-bonus-summary/date_begin/".$cycle[0]."/date_end/".$cycle[1]."/next/yes";
				$this->_redirect($url);
			}elseif($_POST['pay_method'] == 2){
				$url = "http://".WEB_IP."/repairparts/repair-wizard-new-bonus-summary/date_begin/".$cycle[0]."/date_end/".$cycle[1]."/next/yes";
				$this->_redirect($url);
			}
			
		}
		if(isset($_POST['jump'])){
			$url = "http://".WEB_IP."/repairparts/repair-wizard-all-summary/";
			$this->_redirect($url);
		}
	}
	
	public function repairWizardNewAddStockLostAction(){
		$shopList = unserialize(ARR_SHOP_GROUP);
		$periodBegin = $this->_getParam("date_begin");
		$periodEnd = $this->_getParam("date_end");
		$cycle = unserialize(BONUS_CYCLE_2015);
		$this->view->dateBegin = $periodBegin;
		$this->view->dateEnd = $periodEnd;
		$nextCheck = $this->_getParam("next");
		
		foreach($cycle as $k2 => $v2){
			if($periodBegin >= $v2[0] && $periodEnd <= $v2[1] ){
				$cycleKey = $k2;
			}
		
		}
		$this->view->cycle = $cycleKey + 1;
		if($nextCheck == 'yes'){
			$check = true;
			$this->view->nextCheck = $check;
		}
		
		
		$bos = new Model_Payroll_Shopgroupbonus();
		
		$ShopLost = array();
		foreach($shopList as $k => $v){
			if($k != 1 && $k != 6 && $k != 7 && $k != 17){
			$tmpArr = array();
			$stockLost = $bos->getStockLostByShopIdByType($k, $periodBegin, $periodEnd,8);
			$tmpArr['shop_id'] = $k;
			$tmpArr['shop_code']  = $v;
			$tmpArr['before_stocklost'] = $stockLost['amt_total_bonus'];
			$ShopLost[] = $tmpArr;
			}
		}
		$this->view->stocklost = $ShopLost;
		
		if(isset($_POST['button'])){
			$newStockLost = array();
			foreach($_POST['shop_code'] as $key => $val){
				$bosCheck = $bos->getStockLostByShopIdByType($key, $periodBegin, $periodEnd, 7);
				if(!$bosCheck){
					$bos->newShopbonus($key, 7, $periodBegin." current Repair lost", $_POST['current_stocklost'][$key], $_POST['current_stocklost'][$key], 0, 0, $periodBegin, $periodEnd, '0000-00-00', 0, '1111-01-01', 'none',$val);
				}else{
					$bos->updateAdjStockLost($bosCheck['id_bonus'], $_POST['current_stocklost'][$key], $_POST['current_stocklost'][$key]);
				}
				$tmpArr2 = array();
				$bfstockLost = $bos->getStockLostByShopIdByType($key, $periodBegin, $periodEnd,8);
				$currentStockLost = $bos->getStockLostByShopIdByType($key, $periodBegin, $periodEnd, 7);
				$tmpArr2['shop_id']  = $key;
				$tmpArr2['shop_code']  = $val;
				$tmpArr2['before_stocklost'] = $bfstockLost['amt_total_bonus'];
				$tmpArr2['current_stocklost'] = $currentStockLost['amt_total_bonus'];
				$newStockLost[] = $tmpArr2;
			}
			
			$this->view->newStockLost = $newStockLost;
			echo "Add Repair stock lost success";
		}
		
		if(isset($_POST['next'])){
			foreach($_POST['shop_code'] as $key => $val){
				$bosCheck = $bos->getStockLostByShopIdByType($key, $periodBegin, $periodEnd, 9);
				if(!$bosCheck){
					$bos->newShopbonus($key, 9, $periodBegin." adjusted Repair lost", $_POST['adj_total'][$key], $_POST['adj_total'][$key], 0, 0, $periodBegin, $periodEnd, '0000-00-00', 0, '1111-01-01', 'none',$val);
				}else{
					$bos->updateAdjStockLost($bosCheck['id_bonus'], $_POST['adj_total'][$key], $_POST['adj_total'][$key]);
				}
			}
			$url = "/repairparts/repair-wizard-new-confirm-total/date_begin/".$periodBegin."/date_end/".$periodEnd."/next/yes";
			$this->_redirect($url);
		}
		
		
	}
	
	public function repairWizardNewDistributionAction(){
		$dateBegin = $this->_getParam("date_begin");
		$dateEnd = $this->_getParam("date_end");
		$cycle = unserialize(BONUS_CYCLE_2015);
		$repairBonus = new Model_Payroll_Shopgrouprepairbonusrecord();
		$stInfo = new Model_DbTable_Roster_Staffinfo();
		$deductLog = new Model_Payroll_Staffdeductlog();
		$stfBonus = new Model_Payroll_Staffbonus();
		
		$nextCheck = $this->_getParam("next");
		foreach($cycle as $k2 => $v2){
			if($dateBegin >= $v2[0] && $dateEnd <= $v2[1] ){
				$cycleKey = $k2 +1;
			}
	
		}
		if($nextCheck == 'yes'){
			$check = true;
			$this->view->nextCheck = $check;
		}
		$this->view->cycle = $cycleKey;
		$this->view->dateBegin = $dateBegin;
		$this->view->dateEnd = $dateEnd;
	

		$tmprBonus = $repairBonus->getPeriodBonus($dateBegin, $dateEnd);
	
		$rBonus = array();
	
		foreach ($tmprBonus as $k => $v){
			
			if($v['net_bonus'] != 0){
				$rBonus[$v['staff_id']]['bonus']  += $v['net_bonus'];
			}
		}
		
		
		foreach ($rBonus as $k => $v){
			$staffDeduct = $deductLog->getTotalDeductByStaff($k);
			if($staffDeduct && $staffDeduct != 0){
				if($v['bonus'] + $staffDeduct > 0){
					$rBonus[$k]['final_bonus'] = $v['bonus'] + $staffDeduct;
					$rBonus[$k]['deduct_log'] = 0- $staffDeduct;
				}else{
					$rBonus[$k]['final_bonus'] = 0;
					$rBonus[$k]['deduct_log'] = $v['bonus'];
				}
				
				$rBonus[$k]['deduction']  = $staffDeduct;
			}else{
				$rBonus[$k]['final_bonus'] = $v['bonus'];
				$rBonus[$k]['deduct_log'] = 0;
				$rBonus[$k]['deduction']  = 0;
			}
		}
		
		
		$this->view->bonusList = $rBonus;
		if(isset($_POST['submit'])){
			if(!empty($_POST['payList'])){
				$logDate = Model_DatetimeHelper::dateToday();
				foreach ($_POST['payList'] as $stfId => $bonus){
					$staffDetail = $stInfo->getStaffinfo($stfId);
					$staffDeduct = $_POST['deduct_log'][$stfId];
					echo $staffDetail['first_name']." ".$staffDetail['last_name']." Deduct:".$staffDeduct." Final Bonus:".$bonus."<br/>";
					
					
					
					//pay by bank
					if($bonus > 0){
					
						if($staffDetail['id_package'] == 1 || $staffDetail['id_package'] == 3 || $staffDetail['id_package'] == 4 || $staffDetail['id_package'] == 6 || $staffDetail['id_package'] == 7 || $staffDetail['id_package'] == 8){
							$amtBank = round($bonus/1.095,2);
							$amtSuper = round($bonus - $amtBank,2);
							$stfBonus->newStaffbonus($stfId, 1, "Cycle".$cycleKey." Repair Bonus", $bonus, 0, $amtBank, $amtSuper, $dateBegin, $dateEnd, '0000-00-00', 2, '1111-00-00', null);
						}
					//pay by cash
						if($staffDetail['id_package'] == 2 || $staffDetail['id_package'] == 5){
					
							$stfBonus->newStaffbonus($stfId, 1, "Cycle".$cycleKey." Repair Bonus", $bonus, $bonus, 0, 0, $dateBegin, $dateEnd, '0000-00-00', 1, '1111-00-00', null);
						}
					}
					
					if($staffDeduct != 0){
					    $deductLog->addDeduct($stfId, $staffDeduct, $logDate, "Cycle".$cycleKey." Repair Bonus", 'System');
					}
					
				}
				
			}
			
			$url = "http://".WEB_IP."/repairparts/repair-wizard-confirm/date_begin/".$dateBegin."/date_end/".$dateEnd."/next/yes";
			$this->_redirect($url);
		}
	
	}
	
	public function repairWizardNewBonusSummaryAction(){
		$dateBegin = $this->_getParam("date_begin");
		$dateEnd = $this->_getParam("date_end");
		
		$this->view->dateBegin = $dateBegin;
		$this->view->dateEnd = $dateEnd;
		$shopCode = unserialize(ARR_RCENTER_MAPPING);
		$groupCode = unserialize(ARR_SHOP_GROUP_MAPPING_RCENTER);
		$gName = unserialize(ARR_SHOP_GROUP);
		$techList = unserialize(TECH_LIST);
		$rManagerList = unserialize(R_BONUS_MANAGER);
		
		//var_dump($dateBegin);
		$arrRes = array();
		$arrStaff = array();
		$arrShop = array();
		$arrDate = array();
		$goodCase = array();
		$failCase = array();
		$problemCase = array();
		$arrStaff2 = array();
		$arrDate2 = array();
		$invPro = "";
		
		$rJobs = new Model_DbTable_Repairjob();
		
		$rMove = new Model_DbTable_Pr_Prstockmovement();
		$rPart = new Model_DbTable_Pr_Prproducts();
		
		$rStatus = new Model_DbTable_Repairstatusrecord();
		$shopBonus = new Model_Payroll_Shopgrouprepairbonusrecord();
		
		$jList = $rJobs->listAllFinishedJobsByDate($dateBegin, $dateEnd);
		//echo "<pre>";
		
		if(isset($_POST['submit_rule'])){
		foreach($jList as $job){
			
			if($job['repair_staff'] != 380 && empty($job['refund_invoice']) && $job['shop_code'] != 'ADPC' && 
					$job['shop_code'] != 'WLIC' && $job['shop_code'] != 'CLPC'){ 

				$shop =  strtoupper(trim($job["shop_code"]));

				//get parts bottom price
				$partsRes = $rMove->getPartsSummaryByJobId2($job['id_job'],"price_q");
				//$rOpen = $rStatus->isJobReopen($job["id_job"]); //get reopen
				$policyArray = $rJobs->bonusRule($job["id_job"]); //get policy
				//d($partsRes);

				//WHo , what ,finish time , quote , invoices , who record
				$tmpArr = array();
		
				$tmpArr["id_job"] = $job["id_job"];
				$tmpArr["date_start"] =  $job["date_start"];
				$tmpArr["repair_staff"] = $job["repair_staff"];
		
				
		
				$tmpArr["shop_code"] = strtoupper($job["shop_code"]);
		
				$arrShop[] = $job["shop_code"];
		
				$tmpArr["mobile_brand"] = $job["mobile_brand"];
				$tmpArr["mobile_model"] = $job["mobile_model"];
				$tmpArr["quot_price"] = $job["quot_price"];
				$tmpArr["invoice_no"] = $job["invoice_no"];
				$tmpArr["invoice_amt"] = $job["invoice1_price"];
				$tmpArr["invoice_no2"] = $job["invoice_no2"];
				$tmpArr["invoice_amt2"] = $job["invoice2_price"];
				$tmpArr["staff_record"] = $job["staff_record"];
				$tmpArr["time_record"] = $job["time_record"];
				$tmpArr["part_sum"] = $partsRes;
				
				

				$amount = 0;
				$totalCost = 0;
				$bonus = 0;
				
				if($job["invoice_no"]== $job["invoice_no2"]){
					$amount = $job["invoice1_price"];
				}
				else{
					$amount = $job["invoice1_price"] + $job["invoice2_price"];
				}
				
				
				if($job["mobile_brand"] == 'Apple'){
					$bonus = $amount * 0.05;
					if($bonus > 20){
						$bonus = 20;
					}
					
				}else{
					$bonus = $amount * 0.05;
					if($bonus > 20){
						$bonus = 20;
					}
				}
				$tmpArr["bonus"] = $bonus;
				
				if(isset($_POST['rule_contact'])){ //policy contact
					if($policyArray[0]){
						$tmpArr["policy_contact"] = $policyArray[0];
					}else{
						$tmpArr["policy_contact"] = 0;
					}
				}else{
					if($policyArray[0]){
						$tmpArr["policy_contact"] = $policyArray[0];
					}else{
						$tmpArr["policy_contact"] = 0;
						$tmpArr["bonus"] = 0;
					}
				}
				
				if(isset($_POST['rule_custpart'])){ //policy cust part
					if($partsRes[2] == 0){
						$tmpArr["policy_custparts"] = 1;
					}else{
						if($policyArray[1]){
							$tmpArr["policy_custparts"] = $policyArray[1];
						}else{
							$tmpArr["policy_custparts"] = 0;
						}
					}
					
				}else{
					if($partsRes[2] == 0){
						$tmpArr["policy_custparts"] = 1;
					}else{
						if($policyArray[1]){
							$tmpArr["policy_custparts"] = $policyArray[1];
						}else{
							$tmpArr["policy_custparts"] = 0;
							$tmpArr["bonus"] = 0;
						}
					}
					
				}
				
				
				if($job['warranty_check'] == 0){
					$tmpArr["ropen"] = 0;
				}else{
					$tmpArr["ropen"] = 1;
				}
				
				
				if(isset($_POST['rule_fixhq'])){
					if($job['fix_by_hq'] == null){
						$tmpArr["fix_by_hq"] = 0;
					}else{
						$tmpArr["fix_by_hq"] = 1;
					}
				}else{
					if($job['fix_by_hq'] == null){
						$tmpArr["fix_by_hq"] = 0;
					}else{
						$tmpArr["fix_by_hq"] = 1;
						$tmpArr["bonus"] = 0;
					}
				}

				$totalCost = $partsRes[1];
				$tmpArr['apos_charge'] = $amount;
				$tmpArr['parts_cost'] = $totalCost;
				$arrRes[]  = $tmpArr;
			
			}
		}

		$tmpBonusList = array();
		$bonusList = array();
		//d($arrRes);
		/*
		foreach ($arrRes as $k => $v){
			
			if($v['bonus'] > 0 && $v['apos_charge'] >= $v['parts_cost'] && !empty($v['repair_staff']) && $groupCode[$shopCode[$v['shop_code']]][0]){
				if(!empty($v['warranty_by'])){
					if(!in_array($v['warranty_by'], $techList)){
						$tmpBonusList[$groupCode[$shopCode[$v['shop_code']]][0]]['Team'] = 0;
					}else{
						$bonusList[$groupCode[$shopCode[$v['shop_code']]][0]][$v['warranty_by']]	= 0;
					}
					
				}else{
					if(!in_array($v['repair_staff'], $techList)){
						$tmpBonusList[$groupCode[$shopCode[$v['shop_code']]][0]]['Team'] = 0;
					}else{
						$bonusList[$groupCode[$shopCode[$v['shop_code']]][0]][$v['repair_staff']] = 0;
					}
					
				}				
				
			}
		}*/
		
		foreach ($arrRes as $k => $v){
		
			if($v['bonus'] > 0 && $v['apos_charge'] >= $v['parts_cost'] && !empty($v['repair_staff']) && $groupCode[$shopCode[$v['shop_code']]][0]){				
				if(!empty($v['warranty_by'])){
					if(!in_array($v['warranty_by'], $techList)){
						if(!isset($tmpBonusList[$groupCode[$shopCode[$v['shop_code']]][0]]['Team'])){
							$tmpBonusList[$groupCode[$shopCode[$v['shop_code']]][0]]['Team'] = $v['bonus'];
						}else{
							$tmpBonusList[$groupCode[$shopCode[$v['shop_code']]][0]]['Team'] += $v['bonus'];
						}
						
					}else{
						if(!isset($bonusList[$groupCode[$shopCode[$v['shop_code']]][0]][$v['warranty_by']])){
							$bonusList[$groupCode[$shopCode[$v['shop_code']]][0]][$v['warranty_by']] = $v['bonus'];
						}else{
							$bonusList[$groupCode[$shopCode[$v['shop_code']]][0]][$v['warranty_by']] += $v['bonus'];
						}
						
					}
				}else{
					if(!in_array($v['repair_staff'], $techList)){
						if(!isset($tmpBonusList[$groupCode[$shopCode[$v['shop_code']]][0]]['Team'])){
							$tmpBonusList[$groupCode[$shopCode[$v['shop_code']]][0]]['Team'] = $v['bonus'];
						}else{
							$tmpBonusList[$groupCode[$shopCode[$v['shop_code']]][0]]['Team'] += $v['bonus'];
						}
					}else{
						if(!isset($bonusList[$groupCode[$shopCode[$v['shop_code']]][0]][$v['repair_staff']])){
							$bonusList[$groupCode[$shopCode[$v['shop_code']]][0]][$v['repair_staff']] = $v['bonus'];
						}else{
							$bonusList[$groupCode[$shopCode[$v['shop_code']]][0]][$v['repair_staff']] += $v['bonus'];
						}
					}
				}
				
				
				$goodCase[] = $v;
				$arrDate[] = $v['time_record'];
				$arrStaff[] = $v['repair_staff'];
			}else{
				if($v['apos_charge'] < $v['parts_cost']){
					$failCase[] = $v;
					$arrDate2[] = $v['time_record'];
					$arrStaff2[] = $v['repair_staff'];
				}else{
					$problemCase[] = $v;
				}
			}
				
		}
		
		foreach ($tmpBonusList as $groupId => $totalPay){
			if($rManagerList[$groupId]){
				foreach ($rManagerList[$groupId] as $managerId => $percentage){
					if(!isset($bonusList[$groupId][$managerId])){
						$bonusList[$groupId][$managerId] = $totalPay['Team'] * $percentage/ 100;
					}else{
						$bonusList[$groupId][$managerId] += $totalPay['Team'] * $percentage/ 100;
					}
				}
			}
		}
		
		array_multisort($arrStaff,SORT_ASC,$arrDate,SORT_ASC,$goodCase);
		array_multisort($arrStaff2,SORT_ASC,$arrDate2,SORT_ASC,$failCase);
		//var_dump($arrRes);
		//echo "</pre>";
		$this->view->arrRes = $goodCase;
		$this->view->failCase = $failCase;
		$this->view->problemCase = $problemCase;
		d($tmpBonusList);
		d($bonusList);
		//add bonus by staff
			/*
			$stfIn = new Model_DbTable_Roster_Stafflogindetail();
			foreach ($bonusList as $k2 => $v2){
				echo $gName[$k2]."<br/>";
				foreach ($v2 as $stfId => $bAmt){
					$ni = $stfIn->getDetail($stfId);
					//echo $ni['ni'].": ".$bAmt."<br/>";
					$bCheck = $shopBonus->getStaffBonusByDate($stfId, $k2, $dateBegin, $dateEnd);
					if($bCheck){
						$shopBonus->updateBonusRecord($bCheck['id'], $k2, $gName[$k2], round($bAmt,2), $dateBegin, $dateEnd, 0);
					}else{
						if($ni){
							$shopBonus->addBonusRecord($k2, $gName[$k2], round($bAmt,2), $dateBegin, $dateEnd, 0,$stfId);
						}
					}
					
				}
			}*/
		}

	}
	
	public function repairWizardNewConfirmTotalAction(){
		$shopGroup = unserialize(ARR_SHOP_GROUP);
		$bos = new Model_Payroll_Shopgroupbonus();
		$bonusRecord = new Model_Payroll_Shopgrouprepairbonusrecord();
		$periodBegin = $this->_getParam("date_begin");
		$periodEnd = $this->_getParam("date_end");
		$cycle = unserialize(BONUS_CYCLE_2015);
		$this->view->dateBegin = $periodBegin;
		$this->view->dateEnd = $periodEnd;
		$nextCheck = $this->_getParam("next");
		
		foreach($cycle as $k2 => $v2){
			if($periodBegin >= $v2[0] && $periodEnd <= $v2[1] ){
				$cycleKey = $k2;
			}		
		}
		if($nextCheck == 'yes'){
			$check = true;
			$this->view->nextCheck = $check;
		}
		$this->view->cycle = $cycleKey + 1;
		
			$nextCycleBegin = $cycle[$cycleKey + 1][0];
			$nextCycleEnd = $cycle[$cycleKey + 1][1];
			
		$bonusList = array();
		
		foreach($shopGroup as $key => $val){
			if($key != 1 && $key != 6 && $key != 7 && $key != 17){
			$tmpArr2 = array();
			$bonusTotal = 0;
			$adjStockLost = $bos->getStockLostByShopByType($val, $periodBegin, $periodEnd,9);
		
			$tmpArr2['id_shop'] = $key;
			$tmpArr2['shop_code']  = $val;
			$tmpArr2['total_stock_lost'] = $adjStockLost['amt_total_bonus'];
			$totalStockLost = $adjStockLost['amt_total_bonus'];
			
			//get repair bonus
			$bonus = $bonusRecord->getStaffBonusByShopIdDate($key, $periodBegin, $periodEnd);
			
			foreach ($bonus as $k => $v){
				$bonusTotal += $v['final_bonus'];
			}
			
			if($totalStockLost >= 0){
				foreach ($bonus as $k => $v){
					$bonusRecord->updateStfNetBonus($v['id'], round($v['final_bonus'],2));
				}
				$tmpArr2['carry_stock_lost'] = 0;
			}else{
				$carryLost = 0;
				foreach ($bonus as $k => $v){
					$pecent = round($bonusTotal/$v['final_bonus'],2);
					$stfLost = round($totalStockLost/$pecent,2);
					
					if(($v['final_bonus'] + $stfLost) > 0){
						$bonusRecord->updateStfNetBonus($v['id'], round(($v['final_bonus'] + $stfLost),2));
					}else{
						$bonusRecord->updateStfNetBonus($v['id'], 0);
						$carryLost += $v['final_bonus'] + $stfLost;
					}
				}
			
				if($carryLost >= 0){
					$tmpArr2['carry_stock_lost'] = 0;
				}else{
					$tmpArr2['carry_stock_lost'] = $carryLost;
				}
				
			}
			$bonus = $bonusRecord->getStaffBonusByShopIdDate($key, $periodBegin, $periodEnd);
			
			$tmpArr2['bonus_list'] = $bonus;
			
			$bonusList[] = $tmpArr2;
			}
		}
		
		$this->view->bonusList = $bonusList;
		if(isset($_POST['submit'])){
			foreach ($_POST['sBonus'] as $k => $v){
				$bonusRecord->updateStfNetBonus($k, $v);
			}
			
			foreach ($_POST['cStockLost'] as $k => $v){
				
					$bosCheck = $bos->getStockLostByShopByType($v, $nextCycleBegin, $nextCycleEnd, 8);
					if(!$bosCheck){
						$bos->newShopbonus($k, 8, $periodBegin."carryforwardlost", $v, $v, 0, 0, $nextCycleBegin, $nextCycleEnd, '0000-00-00', 0, '0000-00-00', 'none',$shopGroup[$k]);
					}else{
						$bos->updateAdjStockLost($bosCheck['id_bonus'], $v, $v);
					}
			}
			
			$url = "/repairparts/repair-wizard-new-distribution/date_begin/".$periodBegin."/date_end/".$periodEnd."/next/yes";
			$this->_redirect($url);
		}
	}
	
	
	//-------------------------------end of leo seciotn ---------------------------------
	
	/**
	 * This is the report page to tell you how many cost of the shop hold 
	 * if they hold too much parts and did not sale that many 
	 * it should be reduced
	 */
	public function shopPartsCostSummaryAction(){
		
		$arrRCenter = unserialize(ARR_RCENTER_REV_MAPPING);
		$prCategory = new Model_DbTable_Pr_Category();
		$prProducts = new Model_DbTable_Pr_Prproducts();
		$prStock =  new Model_DbTable_Pr_Prstock();
		$prClist = $prCategory->listCategory();
		$this->view->prClist = $prClist; 
		$this->view->arrRCenter  = $arrRCenter;
		
		//d($prClist);
		
		$arrRes = array();
		
		foreach($arrRCenter as $idShop => $v){
			
			// rcenter ID
			foreach($prClist as $k => $title){
				$prList = $prProducts->listProductsByCate($title['id_cate']);
				
				foreach($prList as $pLine){
					$idProduct = $pLine['id_product'];
					$ifScreen = $pLine['is_lcd'];
					$cost = $pLine['price_t'];
					//get stock 
					$stock = $prStock->getShopStock($idProduct, $idShop);
					if($stock >0){
						if($ifScreen){
							if(isset($arrRes[$idShop][$title['id_cate']]['LCD']['QTY'])){
								$arrRes[$idShop][$title['id_cate']]['LCD']['QTY'] +=$stock;
								$arrRes[$idShop][$title['id_cate']]['LCD']['AMT'] += $stock * $cost;
							}
							else{
								
								$arrRes[$idShop][$title['id_cate']]['LCD']['QTY']  =$stock;
								$arrRes[$idShop][$title['id_cate']]['LCD']['AMT']  = $stock * $cost;
							}
	
						}
						else{
							
							if(isset($arrRes[$idShop][$title['id_cate']]['PART']['QTY'])){
								$arrRes[$idShop][$title['id_cate']]['PART']['QTY'] +=$stock;
								$arrRes[$idShop][$title['id_cate']]['PART']['AMT'] += $stock * $cost;
							}
							else{
							
								$arrRes[$idShop][$title['id_cate']]['PART']['QTY']  =$stock;
								$arrRes[$idShop][$title['id_cate']]['PART']['AMT']  = $stock * $cost;
							}							
							
						}
						
					}
					
					
				}
				
			}
		}
		
		//d($arrRes);
		$this->view->arrRes = $arrRes;
		
	}
	/**
	 * this is parts price summary page 
	 * you may modify the parts price then it will update in company info page 
	 */
	
	public function partsPriceSummaryAction(){
		
		// please go verify the price 
		$rProduct = new Model_DbTable_Pr_Prproducts();
		$priceHistory = new Model_DbTable_Pr_Pricehistory();
		
		date_default_timezone_set("Australia/Melbourne");
		
		$firstDay = date("Y-m-1"); 
		
		
		if($_POST){
			
			if(isset($_POST['btn_save']) && $_POST['password'] == 'Office051788' ){
				// only 1,2 can save , other wize not working
				$rList = $rProduct->listAllActive();
				d($rList);
				foreach($rList as $k => $v){
					// all active prducts should have a price >0
					
					$priceHistory->addPricehistory($v['id_product'],$v['act_cost'], $firstDay);
					
				}
				
				
				
			}
			
		}
		
	}
	
	/**
	 * this is to Export the csv of parts cost for manager to double check 
	 * 
	 */
	
	public function exportPartsCostAction(){
		
		$rProduct = new Model_DbTable_Pr_Prproducts();
		$rList = $rProduct->listAllActive();
		
		$fileName = "parts_cost".Model_DatetimeHelper::dateToday().".csv";
		$fl = fopen($fileName,"a");
		fputcsv($fl, array("ID","CODE","TITLE","COST"));
		//foreach($r)
		foreach($rList as $k => $v){
			
			$arrTmp = array($v['id_product'],$v['code_product'],$v['title_product'],$v['act_cost']);
			fputcsv($fl, $arrTmp);
		}
		fclose($fl);
		
		echo "Cost Export";
		
	}
	
	/**
	 * this is the function to summary the total parts back order 
	 */
	public function partsBackOrderSummaryAction(){
		
		$bo = new Model_DbTable_Pr_Backorder();
		$boList = $bo->listAllNotFullfilled();
		
		$arrParts = array();
		
		foreach($boList as $k => $v){
			if(in_array($v['code_product'],$arrParts)){
				$key = array_search($v['code_product'], $arrParts,true);
				$arrParts[$key + 1] += ($v['modify_qty'] == '')?$v['qty_bo']:$v['modify_qty'];
				$arrParts[$key + 2][] = array($v['id_shop'],$v['bo_date']);
				
			}else{
				$arrParts[]=$v['code_product'];
				$arrParts[]= ($v['modify_qty'] == '')?$v['qty_bo']:$v['modify_qty'];
				$tmpArr = array();
				$tmpArr[] =  array($v['id_shop'],$v['bo_date']);
				$arrParts[] = $tmpArr;
			}
		}
		
		$this->view->arrParts = array_chunk($arrParts,3);
		// get all bo Not full filled 
		
		//d($arrParts);
	}
	/**
	 * this is the function to calculate the parts back order 
	 */
	public function partsBackOrderCalculationAction(){
		
		$pbo = new Model_DbTable_Pr_Backorder();
		
		$idShop = 1;
		$arrParts = $pbo->boPartsList($idShop);
		
		foreach($arrParts as $codeProduct){
			
			$boList = $pbo->getAllNotFullfilledBo($codeProduct, $idShop);
			
			// find oldest bo record the id 
			// get all arrange and all allocate 
			// update back no and remove rest 
			$oldID = '';
			$removeID = array();
			
			$tQtyOrder = 0;
			$tQtyAllo = 0;
			
			foreach($boList as $k => $v){
				
				if($oldID == ''){
					
					$oldID = $v['id_bo'];
				}
				else{
					
					$removeID[] =  $v['id_bo'];
				}
				
				$tQtyOrder += $v['qty_act_order'];
				$tQtyAllo  += $v['qty_allocate'];
				
			}	
			
			$totalBo = $tQtyOrder - $tQtyAllo;
			
			$pbo->updateBoQty($oldID, $totalBo);
			foreach($removeID as $idBo){
				
				$pbo->deleteBackorder($idBo);
			}
			
			
		}
		// tehre is only one back order 
		// if back order fullfilled remove it 
		// if back order Not fullfilled combine it 
		// if there is back order , you can modify it 
		// but you can not order  
	}
	
	/**
	 * this is for manage bottom price rate 
	 * the rate is define in table when 
	 * the bottom price rate is changes 
	 * the bottom price must be calcualate again 
	 */
	public function manageBottomPriceRateAction(){
		
		$prCate = new Model_DbTable_Pr_Category();
		if($_POST){
			
			foreach($_POST['rate'] as $k => $v){
				$prCate->udpateCategoryRate($k, $v);
			}
		}
		
		
		$this->view->prList = $prList = $prCate->listCategory();
		
	}
	
	/**
	 * This is the function to re-calcualte the bottom price 
	 */
	public function updateBottomPriceAction(){
		// if price T is NULL, just Ignore it 
		
		$prProducts = new Model_DbTable_Pr_Prproducts();
		$prCategory = new Model_DbTable_Pr_Category();
		
		$pList = $prProducts->listAllActive();
		
		foreach($pList as $prRow){
			
			$priceT = $prRow['price_t'];
			$priceA = $prRow['price_a'];
			
			$id = $prRow['id_cate'];
			
			if($priceT!=''){

				if($prRow['is_lcd']){
				$rate = $prCategory->getCategory($id);
				$priceQ = ceil(($priceT*1.1 + 7.5)* (1 + $rate['rate_price']/100));
				if($priceQ > $priceA){
					
					$priceQ = $priceA;
				}
				$prProducts->updateSinglePrice($prRow['id_product'],'price_q', $priceQ);
				}
				else{
					// it is parts
					$priceQ = ceil($priceT*1.1 + 30);
					if($priceQ > $priceA){
							
						$priceQ = $priceA;
					}	
					$prProducts->updateSinglePrice($prRow['id_product'],'price_q', $priceQ);
				}
				
			}
			
		}
		
		echo "Price Updated!";
			
	}
	/**
	 * 
	 * as request , stand along create barcode function 
	 * create a GRN with 0 stock for the barcode 
	 * 
	 */
	
	public function createBarcodeAction(){
		
		
	}
	
	/**
	 * These functions made by leo
	 */
	public function preWillBarcodeAction(){
		$idJob = $this->_getParam("idjob");
		$skMove = new Model_DbTable_Pr_Prstockmovement();
		$this->view->resList = $skMove->listByNoteId($idJob);
		$this->view->idJob = $idJob;
	}
	
	public function willBarcodeAction(){
		if($_POST){
			$tmprintArray = array();
			$printArray = array();
			foreach ($_POST['checkBox'] as $k => $v){
				for($i = 0; $i < $v; $i++){
					array_push($tmprintArray, $k);
				}
			}
				
			$printArray = array_chunk($tmprintArray, 5);
			$this->view->printArray = $printArray;
		}
	}

}
?>